我有一张这样的桌子:
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那么,有没有人有什么建议呢?谢谢!
发布于 2019-04-16 15:01:03
使用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 发布于 2019-04-16 15:01:25
如果您的数据库管理系统支持,请使用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发布于 2019-04-16 15:04:52
您的解决方案非常有趣。你只需要像这样结束
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这应该适用于当今大多数数据库系统(与窗口函数相比)。但是,如果您要读取表的很大一部分,则窗口函数往往是更有效的解决方案。
https://stackoverflow.com/questions/55702256
复制相似问题