我有以下查询:
SELECT
DATE_FORMAT( DATE, '%M' ) AS MONTH,
DATE_FORMAT( DATE, '%y' ) AS YEAR,
DEVICE,
COUNT( * ) AS cnt
FROM users
GROUP BY YEAR, MONTH, DEVICE
我正在尝试按年和月订购,例如:
- 11 月 11 日
- 12月11日
- 1 月 12 日
- ...
我怎样才能做到这一点?
您可以使用 MySQLYEAR
和MONTH
内部的GROUP
andORDER BY
子句:
SELECT
DATE_FORMAT( DATE, '%M' ) AS MONTH,
DATE_FORMAT( DATE, '%y' ) AS YEAR,
DEVICE,
COUNT( * ) AS cnt
FROM users
GROUP BY YEAR(DATE), MONTH(DATE), DEVICE
ORDER BY YEAR(DATE), MONTH(DATE)
您也可以替换DATE_FORMAT( DATE, '%y' )
为YEAR(DATE)
。
要订购您想要的东西,请使用ORDER BY:
SELECT DATE_FORMAT( DATE, '%M' ) AS
MONTH , DATE_FORMAT( DATE, '%y' ) AS year, DEVICE, COUNT( * ) AS cnt
FROM users
GROUP BY year, MONTH , DEVICE
ORDER BY DATE_FORMAT( DATE, '%y' ), DATE_FORMAT( DATE, '%m' )