简体   繁体   English

从日期字符串计算上个月和下个月

[英]Calculate previous and next months from date string

I'm trying to find the Sales average before and after for selected months over a span of 3 years.我试图找到 3 年跨度内选定月份之前和之后的平均销售额。

There are two columns, MONTH and SELECTED_MONTH .有两列, MONTHSELECTED_MONTH Both of these are in the same format which is string (eg. 201103 ).这两者都采用相同的格式,即字符串(例如201103 )。 I need to select the particular month in SELECTED_MONTH and get the previous and next month of that month in MONTH .我需要在SELECTED_MONTH选择特定月份并在MONTH获取该月的上个月和下个月。

For example: I have 201103 in SELECTED_MONTH .例如:我在SELECTED_MONTH201103 I need to get the previous and next months in MONTH using that value, so 201102 and 201104 .我需要使用该值获取MONTH 201102201104 ,因此201102201104

Any help would be appreciated.任何帮助,将不胜感激。 I tried different ways which won't work.我尝试了不同的方法,但都行不通。 I use HIVE but even queries in SQL would help.我使用 HIVE,但即使在 SQL 中查询也会有所帮助。

MySQL offers powerful, but slightly clunky, date arithmetic functions. MySQL 提供了强大但稍显笨拙的日期算术函数。 The functions STR_TO_DATE() and DATE_FORMAT() allow translation from dates represented as text strings to the DBMS's internal DATE and DATETIME formats.函数STR_TO_DATE()DATE_FORMAT()允许将表示为文本字符串的日期转换为 DBMS 的内部DATEDATETIME格式。

If you happen to have a text column, called, for example, month , in your SQL table, with text dates of the form 201503 ( YYYYmm ), you can use MySQL date arithmetic to do what you want.如果您的 SQL 表中碰巧有一个文本列,例如,名为month ,文本日期格式为201503 ( YYYYmm ),您可以使用 MySQL 日期算法来执行您想要的操作。

STR_TO_DATE(CONCAT(month,'01'),'%Y%m%d') 

produces the DATE of the first day of the month mentioned.产生所提及月份的第一天的 DATE。

LAST_DAY(STR_TO_DATE(CONCAT(month,'01'),'%Y%m%d')) 

produces the date of the last day of month .产生month的最后一天的日期。

STR_TO_DATE(CONCAT(month,'01'),'%Y%m%d') - INTERVAL 1 MONTH

produces the DATE of the first day of the preceding month.产生上个月第一天的 DATE。

STR_TO_DATE(CONCAT(month,'01'),'%Y%m%d') + INTERVAL 1 MONTH

produces the DATE of the first day of the next month.产生下个月第一天的 DATE。

Carrying this a little further, you can get the YYYYmm format for the first day of the preceding quarter like this.再进一步,您可以像这样获得上一季度第一天的YYYYmm格式。

DATE_FORMAT(STR_TO_DATE(CONCAT('201505','01'),'%Y%m%d') - INTERVAL 1 QUARTER, '%Y%m')

The monkey business of converting between text-string dates and internal dates drives most database designers to store date values internally columns that have the DATE datatype.在文本字符串日期和内部日期之间转换的麻烦事促使大多数数据库设计人员在具有DATE数据类型的列内部存储日期值。

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

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