关于mysql:在Group By之前排序

Order By before a Group By

本问题已经有最佳答案,请猛点这里访问。

我需要在几千条记录上提取一些数据,但是我无法对结果进行排序。

1
2
3
4
5
SELECT IdCode, GROUP_CONCAT(' ',CONCAT(MONTHNAME(ei.StartDatetime),' ',YEAR(ei.StartDatetime)))
FROM exclusion_import_data eid JOIN exclusion_import ei ON ei.ImportId = eid.ImportId
WHERE ( IdCode IN ( '84277', '253533' ))  
GROUP BY IdCode
ORDER BY RecordId ASC;

基本上我想看看我们的系统中出现了哪些月份的特定记录。

253533 May 2013, November 2013, December 2013, January 2014, February
2014, March 2014, April 2014, May 2014, June 2014, August 2014,
October 2013, September 2013, June 2013, July 2013, May 2013, August
2013 84277 September 2013, April 2014, May 2013, May 2014, June 2014,
May 2013, March 2014, June 2013, February 2014, January 2014, July
2013, December 2013, November 2013, August 2013, October 2013, August
2014

上面的查询返回正确的月份,由idCodes分隔,但月份全部乱序。

如何在对记录进行分组之前对记录进行排序?


使用group_concat()中的order by选项:

1
2
3
4
5
6
7
8
9
SELECT IdCode,
       GROUP_CONCAT(' ', CONCAT(MONTHNAME(ei.StartDatetime),' ',YEAR(ei.StartDatetime))
                    ORDER BY ei.StartDatetime)
FROM exclusion_import_data eid JOIN
     exclusion_import ei
     ON ei.ImportId = eid.ImportId
WHERE ( IdCode IN ( '84277', '253533' ))
GROUP BY IdCode
ORDER BY RecordId ASC;

您可以在GROUP_CONCAT函数中指定排序,例如:

1
2
GROUP_CONCAT(DATE_FORMAT(ei.StartDatetime,'%M %Y') ORDER BY ei.StartDatetime)
                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^

(我的偏好是通过单个函数调用获得月份和年份,以及对列的一个引用,而不是三个函数调用和对同一列的两个引用。我已经在上面证明了这一点。)

参考:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat