SQL Order By Count(SQL 按计数排序)
问题描述
如果我有这样的表格和数据:
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
并且我希望按照 Group 的总数从小到大排序,例如: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 按计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL 按计数排序
基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
