简体   繁体   中英

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

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.

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. 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')

参考链接

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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