Sql 检索每组第二高的计数
我有一张这样的桌子:Sql 检索每组第二高的计数,sql,greatest-n-per-group,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
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
where supply_count NOT IN (select max(supply_count) from supply)
shopID supply_count
1 10
2 12
3 2
4 11
我使用了not in函数,如下所示:
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
where supply_count NOT IN (select max(supply_count) from supply)
shopID supply_count
1 10
2 12
3 2
4 11
但是,只有第一行显示结果中的第二高值,其他行仍显示最高计数:
shopID supply_count
1 10
2 12
3 5
4 15
我的预期结果是找到每个店铺的第二高供应量,如下所示:
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
where supply_count NOT IN (select max(supply_count) from supply)
shopID supply_count
1 10
2 12
3 2
4 11
有人有什么建议吗?谢谢 使用行编号()
使用行编号()
如果您的dbms支持,请使用行号
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
如果您的dbms支持,请使用行号
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 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
这应该适用于当今大多数数据库系统(与窗口函数相比)。但是,如果要阅读表格的大部分内容,窗口函数往往是一种更有效的解决方案。在某些情况下,只需对结果进行排序和限制即可:
从商店选择suply\u count
按suply_count DESC limit 1,1订购;
在某些情况下,仅对结果进行排序和限制可能很有用:
从商店选择suply\u count
按suply_count DESC limit 1,1订购;
请提供您已检索的查询Tag数据库服务器查看答案请提供您已检索的查询Tag数据库服务器查看答案使用您的查询shopId=2的输出将是什么使用您的查询shopId=2的输出我尝试了此解决方案,效果非常好。但这里的“按供应量计算的订单”应按降序排列。无论如何,谢谢你的帮助!我尝试了这个解决方案,效果非常好。但这里的“按供应量计算的订单”应按降序排列。无论如何,谢谢你的帮助!