For people who would like to output a DATETIME
rather than a month/year combo, here's another way to solve the problem. The benefit of using DATETIME
is that it can easily be plugged into data visualization libraries and tools.
SELECT
LAST_DAY(FROM_UNIXTIME(date_assigned)),
COUNT(*)
FROM assignments
GROUP BY 1
ORDER BY 1 DESC
The LAST_DAY()
function returns the last day of the month for a given DATE
or DATETIME
value. If you'd rather grab the first day, you could select this instead: ADDDATE(LAST_DAY(SUBDATE(FROM_UNIXTIME(date_assigned), INTERVAL 1 MONTH)), 1)
. It adds a day to the last date then subtracts a month.
The 1
values are column position integers -- shorthand so we don't have to type LAST_DAY(FROM_UNIXTIME(date_assigned))
any more than we need to (they start at 1, not 0).
Example output:
|-------------------------------------------|------------------|
| LAST_DAY(FROM_UNIXTIME(date_assigned)) | COUNT(*) |
|-------------------------------------------|------------------|
| September 30, 2020, 12:00 AM | 34 |
|-------------------------------------------|------------------|
| August 31, 2020, 12:00 AM | 23 |
|-------------------------------------------|------------------|