hive sql 获取某天所在月的最后一个星期天

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;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值