如何计算蜂巢之间的月份?

时间:2017-01-04 13:33:45

标签: date hive

有没有办法根据月份和年份计算两个日期之间的月份

例如 2016-01-01 2017-01-22

我需要在hive中以整数格式返回12

3 个答案:

答案 0 :(得分:2)

自Hive 1.2.0

以来,UDF之间可以使用

个月_

https://issues.apache.org/jira/browse/HIVE-9518

手册在这里:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

months_between需要注意几天,而不仅仅是年和月:

hive> select abs(cast(months_between('2016-01-10', '2017-01-10')as int));
OK
12
Time taken: 1.812 seconds, Fetched: 1 row(s)

hive> select abs(cast(months_between('2016-01-10', '2017-01-01')as int));
OK
11
Time taken: 0.084 seconds, Fetched: 1 row(s)

如果您希望它完全根据月份和年份进行计算,请使用trunc()函数:

hive> select abs(cast(months_between(trunc('2016-01-10','MM'), trunc('2017-01-01','MM'))as int));
OK
12
Time taken: 0.123 seconds, Fetched: 1 row(s)

答案 1 :(得分:0)

可以编写自己的UDF,它会执行类似的操作 -

  1. 将日期转换为unix时间戳
  2. 从较低的
  3. 中删除较高的时间戳
  4. 结果是两个日期之间的持续时间
  5. 将结果除以(60秒* 60分钟* 24小时* 30天)以获得月份

答案 2 :(得分:0)

你能否在日常考虑中使用以下内容

select (cast(year('2017-01-22') as int) - cast(year('2016-01-01') as int) )*12 +  (cast(month('2017-01-22') as int) - cast(month('2016-01-01') as int) )  +  IF(day('2017-01-22')  > day('2016-01-01'), 1, 0 )  

没有白天考虑

select (cast(year('2017-01-22') as int) - cast(year('2016-01-01') as int) )*12 +  (cast(month('2017-01-22') as int) - cast(month('2016-01-01') as int) ) 
相关问题