首页 > 解决方案 > HiveQL 选择特定日期范围内的生日

问题描述

我有下表persons

id name   location dob
1  John   NY       1978-08-02
2  Nancy  LA       1993-10-12
3  Smith  GA       1986-09-25
4  Emily  MN       1988-04-14
5  Lily   MN       1978-11-02

如何编写 HiveQL 来选择当前日期和 2 个月前之间的生日:

例如,

select current_date
>> 2018-09-27

select add_months(current_date,-2);
>> 2018-07-27

birthdays在这些日期之间选择

id name   location dob
1  John   NY       1978-08-02
3  Smith  GA       1986-09-25

标签: sqlhivehiveql

解决方案


生日问题很棘手:

select t.*
from t
where (year(current_date) = year(add_months(current_date, -2)) and
       date_format(dob, 'MM-DD') between date_format(add_months(current_date, -2), 'MM-DD') and date_format(current_date, 'MM-DD')
      ) or
      (year(current_date) > year(add_months(current_date, -2)) and
       date_format(dob, 'MM-DD') not between date_format(current_date, 'MM-DD') and date_format(add_months(current_date, -2), 'MM-DD')
      ) 

基本上,您只需要比较月份和日期,而不是年份。然后,您必须考虑期限何时超过一年。


推荐阅读