Reputation: 11
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
Upvotes: 0
Views: 102
Reputation: 522762
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:
Upvotes: 2