Hive sql之interval 1 month

当前日期(2020-11-02)
步骤一:
select
current_date - interval 1 day,
current_date - interval 2 day,
current_date - interval 3 day,
current_date - interval 4 day
结果为:
2020-11-01 00:00:00
2020-10-31 00:00:00
2020-10-30 00:00:00
2020-10-29 00:00:00
发现没问题;

步骤二:
select
current_date - interval 1 day - interval 1 month,
current_date - interval 2 day - interval 1 month,
current_date - interval 3 day - interval 1 month,
current_date - interval 4 day - interval 1 month
结果为:
2020-10-01 00:00:00
2020-10-01 00:00:00
2020-09-30 00:00:00
2020-09-29 00:00:00

问题来了,2020-10-31减一个月,依然是10月,猜测31号用该函数减1个月,仍然为本月初。

步骤三:验证
select
current_date - interval 1 day - interval 2 month,
current_date - interval 2 day - interval 2 month,
current_date - interval 3 day - interval 2 month,
current_date - interval 4 day - interval 2 month
结果为:
2020-09-01 00:00:00
2020-08-31 00:00:00
2020-08-30 00:00:00
2020-08-29 00:00:00
是不是很奇怪,接下来,试着先把顺序换一换,看能不能改变;

步骤四:
select
current_date - interval 1 month - interval 1 day ,
current_date - interval 1 month - interval 2 day ,
current_date - interval 1 month - interval 3 day ,
current_date - interval 1 month - interval 4 day
结果为:
2020-10-01 00:00:00
2020-09-30 00:00:00
2020-09-29 00:00:00
2020-09-28 00:00:00

完美解决!!!

综合步骤一与步骤四,可总结如下:

多重日期减法时候,按年、月、日的顺序去减,可避免出错

你可能感兴趣的:(HQL)