架构:
Cereal
Cereal_name
Buyer_name
Cereal_name
是谷物的名称
Buyer_name
是带来某种麦片的买家
我试图列出每种谷物及其购买次数,然后找到前4种谷物:答案的例子是:
'HoneyNut' 400
'Cap'n Crunch' 400
'Chocolate Flakes' 300
'Frosted Flakes' 200
注意:有4个,因为其中一个具有相同的数字
我拥有的是:
Select Cereal_name, count(*) as numOfCount
From Cereal
Group By numOfCount Desc
我想使用rowNum<=3
,但在这种情况下无法使用
提前致谢!
答案 0 :(得分:2)
尝试:
SELECT * FROM
(SELECT
Cereal_name,
COUNT(*) as numOfCount
FROM Cereal
GROUP BY numOfCount
ORDER BY COUNT(*) DESC
) CEREALS
WHERE ROWNUM <= 3
我认为是甲骨文。
DB2:
可能是这个,但我不确定:
SELECT
Cereal_name,
COUNT(*) as numOfCount
FROM Cereal
GROUP BY numOfCount
ORDER BY COUNT(*) DESC
FETCH FIRST 3 ROWS ONLY
答案 1 :(得分:1)
如果你不能使用DB2的兼容模式,那么使用标准的ANSI SQL窗口函数应该可以实现:
select * from ( select t1.*, dense_rank() over (order by cereal_count) as rank from ( select cereal_name, count(*) as cereal_count from cereal group by cereal_name ) t1 ) t2 where rank <= 3 order by rank desc
答案 2 :(得分:1)
也许这个?
SELECT G.Cereal_name, G.numOfCount
FROM (
Select Cereal_name, count(*) as numOfCount
From Cereal
Group By Cereal_name) G
inner join (
Select DISTINCT count(*) as numOfCount
From Cereal
Group By Cereal_name
order by numOfCount Desc
FETCH FIRST 3 ROWS ONLY) C on C.numOfCount = G.numOfCount
order by G.numOfCount DESC