SQL Order By Count [英] SQL Order By Count

查看:228
本文介绍了SQL Order By Count的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的表和数据:

If I have a table and data like this:

ID |  Name  |  Group   

1    Apple     A    

2    Boy       A

3    Cat       B

4    Dog       C

5    Elep      C

6    Fish      C

根据组从最小到最大值的总和排序,例如:
A - 2条记录,B - 1条记录,C - 3条记录,因此它将变为:

and I wish to order it according to the total of Group from smallest to largest value, such as : A - 2 records , B - 1 record , C - 3 records , so it will become:

3    Cat       B

1    Apple     A    

2    Boy       A

4    Dog       C

5    Elep      C

6    Fish      C

我尝试了

    $sql = "SELECT ID,Name FROM table ORDER BY COUNT(Group)";

但它只为我返回一个结果。

but it just returns one result for me.

有什么提示吗?谢谢。

推荐答案

您需要先聚合数据,可以使用GROUP BY子句:

You need to aggregate the data first, this can be done using the GROUP BY clause:

SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC

DESC关键字允许您首先显示最高计数,按默认顺序以升序显示ORDER BY这将首先显示最低计数。

The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.

这篇关于SQL Order By Count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆