在分组之前排序[重复]
Posted
技术标签:
【中文标题】在分组之前排序[重复]【英文标题】:Order By before a Group By [duplicate] 【发布时间】:2014-11-05 13:49:42 【问题描述】:我需要从几千条记录中提取一些数据,但我无法对结果进行排序。
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 2013 年 5 月、2013 年 11 月、2013 年 12 月、2014 年 1 月、2 月 2014 年 2014 年 3 月 2014 年 4 月 2014 年 5 月 2014 年 6 月 2014 年 8 月 2013 年 10 月、2013 年 9 月、2013 年 6 月、2013 年 7 月、2013 年 5 月、8 月 2013 84277 2013 年 9 月,2014 年 4 月,2013 年 5 月,2014 年 5 月,2014 年 6 月, 2013 年 5 月、2014 年 3 月、2013 年 6 月、2014 年 2 月、2014 年 1 月、7 月 2013 年 2013 年 12 月 2013 年 11 月 2013 年 8 月 2013 年 10 月 8 月 2014
上面的查询返回正确的月份,用idCodes分隔,但是月份都是乱序的。
如何在分组之前对记录进行排序?
【问题讨论】:
管理摘要:您可以group_concat(myfield ORDER BY myfield ASC)
,因此在您的情况下将ORDER BY ei.StartDateTime
添加到group_concat
。
【参考方案1】:
使用order by
选项在 group_concat()
:
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;
【讨论】:
【参考方案2】:您可以在GROUP_CONCAT
函数中指定排序,例如:
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
【讨论】:
完美。非常感谢!以上是关于在分组之前排序[重复]的主要内容,如果未能解决你的问题,请参考以下文章