hive sql找到本月的最后一个星期天,其余时间查找也可参考类似的思路
主要思路就是通过找到当月的最后一天属于周几,然后往前推到本月的最后一个星期天;其中找到当月最后一天时通过下月第一天往前推一天,需考虑该月是否为12月等等情况,具体hive sql如下:
--先找到下个月的第一天,根据年月日确定当月最后一天的日期
drop table if exists month_last_day_table;
create table if not exists month_last_day_table as
select
date_sub(
concat(
concat(
(case when month(current_date())=12 then year(current_date())+1 else year(current_date()) end), --年
'-',
(case when month(current_date())=12 then '01'
when month(current_date())=11 then '12'
else concat('0',month(current_date())+1) end)), --月
'-',
'01'), --日
1) as month_last_day;
--获取当月最后一个星期天,判断当月最后一天属于周几,随后往前推到第一个星期天
drop table if exists month_last_sunday;
create table if not exists month_last_sunday as
select
case
when time_judge =0 then month_last_day
when time_judge =1 then date_sub(month_last_day,1)
when time_judge =2 then date_sub(month_last_day,2)
when time_judge =3 then date_sub(month_last_day,3)
when time_judge =4 then date_sub(month_last_day,4)
when time_judge =5 then date_sub(month_last_day,5)
when time_judge =6 then date_sub(month_last_day,6)
end as last_sunday
from
(select
pmod(datediff(month_last_day, to_date('1920-01-01')) - 3, 7) as time_judge,month_last_day --判断当月最后一天属于周几
from month_last_day_table ) t;