[英]Retrieve 2nd highest count by each group
我有一張這樣的表:
shopID supplier supply_count
1 a 12
1 b 10
1 c 8
1 d 7
2 b 12
2 f 12
2 e 10
3 b 5
3 a 2
4 f 15
4 c 11
我使用了 not in 函數,如下所示:
where supply_count NOT IN (select max(supply_count) from supply)
但是,只有第一行顯示結果中的第二個最高值,其他行仍然顯示最高計數:
shopID supply_count
1 10
2 12
3 5
4 15
我的預期結果是找到每個商店的第二大供應數量,如下所示:
shopID supply_count
1 10
2 12
3 2
4 11
那么,有人有一些建議嗎? 謝謝!
使用row_number()
select shopid,supply_count
from
(
select shopID,supply_count,row_number() over(partition by shopID order by supply_count) as rn
from tablename
)A where rn=2
如果您的 dbms 支持,請使用 row_number
with cte as
(
select *,row_number() over(partition by shopID order by supply_count desc) rn from table_name
) select * from cte where rn=2
你的解決方案很有趣。 你只需要像這樣完成
select s1.shopId, max(s1.supply_count)
from supply s1
where supply_count NOT IN (
select max(supply_count)
from supply s2
where s1.shopId = s2.shopId
)
group by s1.shopId
這應該適用於當今大多數數據庫系統(與窗口函數相比)。 但是,如果您將閱讀表格的很大一部分,則窗口函數往往是一種更有效的解決方案。
在某些情況下,僅排序和限制結果可能很有用:
SELECT suply_count FROM shop
ORDER BY suply_count DESC limit 1,1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.