hive3中现在支持了
select trunc(‘2021-03-01’,‘Q’)
即可获得当前季度第一天,但是低版本的还是要自己实现。
首先可以通过
(floor(substr(current_timestamp,6,2)/3.1)*3)+1 --获取的是本季度的月份
例:select current_timestamp,(floor(substr(current_timestamp,6,2)/3.1)*3)+1
输出:
2020-09-29 22:34:25.533 7
然后通过拼接的方式实现,注意季度月份为1,4,7,10,拼接时需要进行判断。
select concat(year(current_timestamp),
case when (floor(substr(current_timestamp,6,2)/3.1)*3)+1<10 then concat(0,(floor(substr(current_timestamp,6,2)/3.1)*3)+1)
else (floor(substr(current_timestamp,6,2)/3.1)*3)+1 end,'01')
输出结果:20200701
对12月份某日期进行测试:
select concat(year('2020-12-12'),
case when (floor(substr('2020-12-12',6,2)/3.1)*3)+1<10 then concat(0,(floor(substr('2020-12-12',6,2)/3.1)*3)+1)
else (floor(substr('2020-12-12',6,2)/3.1)*3)+1 end,'01')
输出:20201001
注:最后输出结果为string类型使用from_unixtime(unix_timestamp(date,'yyyyMMdd'))可以转换为标准日期格式
例:
select from_unixtime(unix_timestamp(concat(year('2020-12-12'),
case when (floor(substr('2020-12-12',6,2)/3.1)*3)+1<10 then concat(0,(floor(substr('2020-12-12',6,2)/3.1)*3)+1)
else (floor(substr('2020-12-12',6,2)/3.1)*3)+1 end,'01'),'yyyyMMdd')
输出结果:2020-10-01 00:00:00
在Hive的低版本中,如果需要获取当前季度的第一天,可以通过多步计算实现。首先,利用`floor(substr(current_timestamp,6,2)/3.1)*3)+1`计算出本季度的月份,然后根据月份拼接年份和‘01’来得到季度第一天的日期字符串。对于12月的情况,也会正确转化为下个季度的第一天。最后,通过`from_unixtime(unix_timestamp(date,'yyyyMMdd'))`将字符串转换为标准日期格式。
2万+





