找到每个唯一行的前n个

时间:2009-10-26 03:01:13

标签: sql sql-server sql-server-2008 greatest-n-per-group

我正在尝试为表格中的每个唯一数据行获取前N个记录(我在列 b c 上进行分组d ,列 a 是唯一标识符,列 e 是我想要在这种情况下排名前1的分数。)

a    b    c    d    e
2    38   NULL NULL 141
1    38   NULL NULL 10
1    38   1    NULL 10
2    38   1    NULL 1
1    38   1    8    10
2    38   1    8    1
2    38   16   NULL 140
2    38   16   12   140

e.g。从这些数据我想找到以下行:

a    b    c    d    e
2    38   NULL NULL 141
1    38   1    NULL 10
1    38   1    8    10
2    38   16   NULL 140
2    38   16   12   140

有人可以指出我正确的方向来解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

您的示例没有显示,并且您没有解释如何确定哪一行是“顶级”,所以我放了??????在您需要提供排名列的查询中,例如

a desc
例如,

。无论如何,这正是SQL Server 2005及更高版本中的分析功能所适用的。

declare @howmany int = 3;
with TRanked (a,b,c,d,e,rk) as (
  select
    a,b,c,d,e,
    rank() over (
      partition by b,c,d
      order by ???????
    )
  from T
)
  select a,b,c,d,e
  from TRanked
  where rk <= @howmany;

答案 1 :(得分:0)

空值很痛苦,但是像这样:

select * from table1 t1
where a in (
  select top 1 a from table1 t2
  where (t1.b = t2.b or (t1.b is null and t2.b is null))
    and (t1.c = t2.c or (t1.c is null and t2.c is null))
    and (t1.d = t2.d or (t1.d is null and t2.d is null))
  order by e desc
  )

或更好:

select * from (
  select *, seqno = row_number() over (partition by b, c, d order by e desc)
  from table1
  ) a
where seqno = 1

答案 2 :(得分:0)

我相信这会做你所说的(从here扩展这个想法):

select b,c,d,e, 
rank() over 
(partition by b,c,d order by e desc) "rank" 
from t1 where rank < 5

干杯。