0

我正在尝试获取表中每个唯一数据行的前 N ​​条记录(我对列bcd进行分组,列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

例如,从这些数据中,我想找到以下行:

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

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

4

3 回答 3

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;
于 2009-10-26T03:22:42.257 回答
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
于 2009-10-26T03:13:16.003 回答
0

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

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

干杯。

于 2009-10-26T03:30:34.003 回答