如何按不同的字段选择整行,并按不同字段的COUNT对结果进行排序?

时间:2017-07-10 07:46:26

标签: mysql sql

我的方案与此link非常相似,但除Group By [某个字段]外,我还需要按COUNT([某个字段])对结果进行排序。

例如,我可能有这个表:

 Title        Category
 Project 1    Admin
 Project 2    Development
 Project 2    Admin
 Project 3    Development

应用此SQL语句后:

SELECT Title, MIN(Category) AS Category
FROM MyTable
GROUP BY Title

我有:

Project 1    Admin
Project 2    Admin
Project 3    Development

但我还需要根据Title的COUNT()对此进行排序,以便最终得到这个:

Project 2    Admin
Project 1    Admin
Project 3    Development

我怎样才能达到这个效果?

3 个答案:

答案 0 :(得分:1)

COUNT

中使用Order by汇总
SELECT Title, MIN(Category) AS Category
FROM MyTable
GROUP BY Title
Order by count(*) desc,Category

答案 1 :(得分:1)

您可以在count(Title)中使用order by

SELECT Title, MIN(Category) AS Category
FROM MyTable
GROUP BY Title
ORDER BY count(Title) DESC, Title

答案 2 :(得分:1)

ORDER BY子句与COUNT聚合函数

一起使用
SELECT Title, MIN(Category) AS Category
FROM MyTable
GROUP BY Title
Order by count(*) desc,Category