首页 > 解决方案 > 如何按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;

标签: sqloracle

解决方案


我想你想要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.


推荐阅读