【问题标题】:MS SQL agregated with top 2MS SQL 聚合前 2
【发布时间】:2022-12-29 18:41:04
【问题描述】:

我有一个问题如何在 MS SQL 中编写查询以显示每个 id 和部门 (dep) 的前 2 个总数。 这是数据示例:

  id    dep num
288610  101 95
334028  101 64
480492  101 61
259007  102 215
333655  102 177
369079  102 146
128672  102 103
398319  103 247
384462  103 222
448798  103 204
430841  103 133
387829  103 62

和我的选择

select  a.id, a.dep, COUNT(b.units) as num
from id a, DEJAVNOST_SKD b 
where a.id = b.id 
   and b.units is null
group by a.id, a.dep
having COUNT(a.enota) >10
order by  a.dep, COUNT(b.units) desc

结果应该是:

id  dep num
288610  101 95
334028  101 64
259007  102 215
333655  102 177
398319  103 247
384462  103 222

【问题讨论】:

    标签: sql


    【解决方案1】:

    典型的解决方案是使用行号

    select id, dep, num
    from (
        select *, Row_Number() over(partition by dep order by num desc) rn
        from t
    )t
    where rn <= 2;
    

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多