Mysql按日期排序

时间:2016-01-18 07:25:08

标签: mysql

这是我试图获取前30天数据的查询。

    SELECT DAY(calendar.datefield) AS callDay,
    DATE_FORMAT(calendar.datefield,"%d-%m-%Y") AS DataDate,
    COUNT(user_appoint.`id`) AS total_appt,
    SUM(CASE WHEN status_id=6 THEN 1 ELSE 0 END) AS fit,
    SUM(CASE WHEN status_id=7 THEN 1 ELSE 0 END) AS unfit,
    SUM(CASE WHEN status_id=1 THEN 1 ELSE 0 END) AS pending,
    SUM(CASE WHEN status_id=19 THEN 1  ELSE 0 END) AS reexamined
    FROM user_appoint
    RIGHT JOIN calendar ON DATE(user_appoint.`ApptDateTime`) = calendar.`datefield` AND user_appoint.`comp_id` = 123
    WHERE calendar.datefield BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
    # and user_appoint.`comp_id` = 123
    GROUP BY calendar.`datefield`
    ORDER BY datadate ASC  

查询的输出如下: -

 callDay  DataDate    total_appt     fit   unfit  pending  reexamined  
-------  ----------  ----------  ------  ------  -------  ------------
 ...
 14  14-01-2016           0       0       0        0             0
 15  15-01-2016           3       0       0        3             0
 16  16-01-2016           0       0       0        0             0
 17  17-01-2016           0       0       0        0             0
 18  18-01-2016           0       0       0        0             0
 20  20-12-2015           0       0       0        0             0
 21  21-12-2015           0       0       0        0             0
 22  22-12-2015           1       1       0        0             0
 23  23-12-2015           0       0       0        0             0
 ...

这是以升序格式向我提供当月的数据,之后以升序格式提供上个月的数据。我希望上个月的数据以升序格式显示为当前月份的asc格式数据。

1 个答案:

答案 0 :(得分:2)

您按照您从日期创建的字符串进行排序,因此您可以按字母顺序排序。

改为排序日期:

order by calendar.datefield asc;