有一个表T结构和数据如下:
d1   d2
1    1
1    2
1    3
2    1
2    2
2    3
2    4现要对d1进行分组, 每组取出d2倒序的前两条数据, 结果如下所示:d1   d2
1    3
1    2
2    4
2    2
请问该SQL语句怎么写?  谢谢.

解决方案 »

  1.   

    create table test(d1 int,d2 int)
    insert test select 1,1
    union all select 1,2
    union all select 1,3
    union all select 2,1
    union all select 2,2
    union all select 2,3
    union all select 2,4select * from test a where d2 in
    (
    select top 2 d2 from test where d1=a.d1 order by d2 desc
    )
    order by d1,d2 desc
      

  2.   

    select * from
    (
    select t.*,row_number() over(partition by d1 order by d2 desc) rn
    from t
    )tt
    where tt.rn<=2
      

  3.   

    select * from
    (
    select *,(select count(1)+1 from t where t.d1=tt.d1 and t.d2>tt.d2) rn
    from t as tt
    )v
    where rn<=2