检索每个组的第二高计数

时间:2019-04-16 06:55:53

标签: sql greatest-n-per-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

那么,有人有什么建议吗?谢谢!

4 个答案:

答案 0 :(得分:0)

使用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 

答案 1 :(得分:0)

如果您的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

答案 2 :(得分:0)

您的解决方案非常有趣。您只需要像这样完成

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

这在当今大多数数据库系统上都应该有效(与窗口函数相比)。但是,如果您要阅读表的很大一部分,则窗口函数往往是一种更有效的解决方案。

答案 3 :(得分:0)

在某些情况下,仅排序和限制结果可能会有用:

SELECT suply_count FROM shop
ORDER BY suply_count DESC limit 1,1;
相关问题