简体   繁体   English

如何使用 Hive 中的月份计算某个日期

[英]How to calculate certain date using month in Hive

Is there any way to set certain date in the past, using current date in Hive?有没有办法在过去设置某个日期,在 Hive 中使用当前日期? I need to get always first day of previous month at any moment in current month and then using it for filtration我需要在本月的任何时候始终获取上个月的第一天,然后将其用于过滤

Use add_month to get previous month date, use TRUNC to get first day:使用 add_month 获取上个月的日期,使用 TRUNC 获取第一天:

select trunc(add_months(current_date,-1),'MM') --returns 2021-06-01 for current_date = 2021-07-22

If you do not have TRUNC function, then use add_month to get previous month date, use substr to get 'yyyy-MM', concatenate with '-01' to get first day of month:如果您没有 TRUNC 函数,则使用 add_month 获取上个月的日期,使用 substr 获取 'yyyy-MM',与 '-01' 连接以获取该月的第一天:

select concat(substr(add_months(current_date,-1),1,7),'-01') --returns 2021-06-01 for current_date = 2021-07-22

Also you can subtract 2 months, get last_day() and add one day to get previous month first day:您也可以减去 2 个月,获得 last_day() 并添加一天以获得上个月的第一天:

select date_add(last_day(add_months(current_date, -2)),1) --returns 2021-06-01 for current_date = 2021-07-22

And one more simple method:还有一种更简单的方法:

select date_format(add_months(current_date, -1),'yyyy-MM-01') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM