MySQL如何对此查询进行排序?

时间:2012-05-17 09:17:56

标签: mysql sql sorting

我有以下查询:

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日
  • ...

我该怎么做?

2 个答案:

答案 0 :(得分:1)

要订购您想要的商品,请使用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' )

答案 1 :(得分:1)

您可以在GROUPORDER BY子句中使用MySQL YEARMONTH

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)