简体   繁体   English

按日期/月份分组

[英]GROUP BY date/month

I have a table that contains a lot of transactions with the date formatted like this:- 我有一个表,其中包含许多日期格式如下的交易:

January 1, 2016
September 9, 2016
September 13, 2016
August 8, 2017
August 9, 2017

How would I go about grouping the month and year together, when the date is there in the middle - and they are Varchar 当日期在中间时,我将如何将月份和年份分组在一起-它们是Varchar

This is a slightly tricky question. 这是一个棘手的问题。 We can approach this by first converting your date strings to bona-fide dates using STR_TO_DATE , and then going back to strings with DATE_FORMAT to obtain the month and year to be used for grouping your data. 我们可以通过以下方法来解决此问题:首先使用STR_TO_DATE将日期字符串转换为真实日期,然后使用DATE_FORMAT返回字符串以获取用于对数据进行分组的月份和年份。

SELECT
    DATE_FORMAT(STR_TO_DATE(date_col, '%M %e, %Y'), '%Y-%m') AS ym,
    SUM(some_col) AS sum_col
FROM yourTable
GROUP BY
    DATE_FORMAT(STR_TO_DATE(date_col, '%M %e, %Y'), '%Y-%m')

For a better long term solution, consider storing your text dates in some sort of MySQL date column type. 为了获得更好的长期解决方案,请考虑将文本日期存储在某种MySQL日期列类型中。 Another option would be to store dates in an numeric column as seconds since the epoch. 另一种选择是将日期存储在数值列中,以自该纪元以来的秒数为单位。 The above query, while it may be logically correct, probably has no chance of using any index, so from a performance point of view you should try to avoid situations like this. 上面的查询虽然在逻辑上可能是正确的,但可能没有使用任何索引的机会,因此从性能的角度来看,您应尝试避免出现这种情况。

Demo here: 演示在这里:

Rextester 右旋酯

GROUP BY DATE_FORMAT(record_date, '%Y%m')

参考链接

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

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