sql - 如何按Oracle中出现次数最多的项目进行分组
问题描述
我写了以下查询:
SELECT i.* FROM items i
JOIN order_details od ON od.item_id = i.item_id
并得到以下结果:
ITEM_ID NAME DESCRIPTION IMAGE_URL PRICE
------- ------- ----------- --------------------- -----
1 Apple (null) http://www.apple.com 200
1 Apple (null) http://www.apple.com 200
2 Orange (null) http://www.orange.com 200
3 Banana (null) http://www.banana.com 200
3 Banana (null) http://www.banana.com 200
3 Banana (null) http://www.banana.com 200
4 Item-4 (null) http://www.banana.com 200
4 Item-4 (null) http://www.banana.com 200
5 Item-5 (null) http://www.banana.com 200
6 Item-6 (null) http://www.banana.com 200
我需要以下按出现次数最多的结果排序:
NAME PRICE
------- -----
Banana 200
Apple 200
Item-4 200
Orange 200
Item-5 200
我试过下面的查询,但它不起作用。
SELECT DISTINCT i.name, i.price FROM items i
JOIN order_details od ON od.item_id = i.item_id
GROUP BY i.item_id
WHERE count(*) DESC;
解决方案
我想你想要ORDER BY
,而不是WHERE
:
SELECT i.item_id, i.name, i.price
FROM items i
INNER JOIN order_details od
ON od.item_id = i.item_id
GROUP BY i.item_id, i.name, i.price
ORDER BY COUNT(*) DESC;
请注意,所有未聚合的列都SELECT
需要在GROUP BY
.
推荐阅读
- html - 防止卡片在卡片组中展开
- amazon-web-services - 推送到 ECR 时的 Docker 映像大小与本地不同
- r - 如何绘制时间数据
- javascript - 对象作为Javascript中的函数参数
- amazon-cognito - 如何使用 Terraform 创建 AWS Cognito 用户
- c# - HelixToolkit 和 3d 绘图
- apache-camel - 何时在骆驼 DSL 中使用 end() 和 endChoice()
- time-complexity - 计算递归算法的时间复杂度
- php - Laravel - 事务回滚不起作用
- keras - 计算 3D CNN 的输出形状