【问题标题】:Retrieve 2nd highest count by each group检索每组的第二高计数
【发布时间】:2019-04-16 06:55:52
【问题描述】:

我有一张这样的桌子:

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

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

【问题讨论】:

  • 请提供您尝试过的查询
  • 标签数据库服务器
  • 查看答案here

标签: sql greatest-n-per-group


【解决方案1】:

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

【讨论】:

  • 我试过这个解决方案,效果很好。但在这里:'order by supply_count' 应该按降序排列。无论如何,感谢您的帮助!
【解决方案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

【讨论】:

    【解决方案3】:

    您的解决方案很有趣。你只需要这样完成

    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
    

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

    【讨论】:

    • 使用您的查询,shopId =2 的输出将是什么
    【解决方案4】:

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

    SELECT suply_count FROM shop
    ORDER BY suply_count DESC limit 1,1;
    

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 1970-01-01
      • 2021-06-06
      • 2021-09-29
      • 2016-02-21
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      相关资源
      最近更新 更多