您的位置:程序门 -> ms-sql server -> 基础类



求一条sql语句


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


求一条sql语句[已结贴,结贴人:s_hluo]
发表于:2007-06-20 19:05:44 楼主
有一个表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语句怎么写?     谢谢.

发表于:2007-06-20 19:11:101楼 得分:0
不好意思,   结果写错了,   应该是:
d1       d2
1         3
1         2
2         4
2         3
发表于:2007-06-20 19:11:302楼 得分:0
在线等,   谢谢.
发表于:2007-06-20 19:19:213楼 得分:10
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,4

select   *   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
发表于:2007-06-20 19:19:404楼 得分:5
d1                     d2                    
-----------   -----------  
1                       3
1                       2
2                       4
2                       3
发表于:2007-06-20 19:21:055楼 得分:5
select   *   from

select   t.*,row_number()   over(partition   by   d1   order   by   d2   desc)   rn
from   t
)tt
where   tt.rn <=2
发表于:2007-06-20 19:22:096楼 得分:0
沒看版塊,錯了!!!!
发表于:2007-06-20 19:31:107楼 得分:0
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
发表于:2007-06-20 19:39:318楼 得分:0
谢谢两位,   结贴.


快速检索

最新资讯
热门点击