读书人

根据条件取多组前n条数据解决方案

发布时间: 2012-02-25 10:01:48 作者: rapoo

根据条件取多组前n条数据
表只有两个字段,ID1,ID2

insert into Table1 values(1,1)
insert into Table1 values(2,1)
insert into Table1 values(3,2)
insert into Table1 values(4,3)
insert into Table1 values(5,3)
insert into Table1 values(6,3)

select * from Table1

得到的结果为
ID1ID2
11
21
32
43
53
63

现在假设要取多组前两条数据,希望得到的结果是
ID1ID2
11
21
32
43
53

也就是跟单条语句时的TOP一样,1、2条的全取,超过2条的也只取前两条。

想了一下,觉得自己想得太麻烦了。

希望各位高手不吝指点下。

[解决办法]

SQL code
;with AcHerat as(    select *,rid=row_number() over (partition by id2 order by id1)    from tb)select id1,id2from AcHeratwhere rid <= 2  -- 就是n
[解决办法]
SQL code
select id1,id2 from (select row_number()over(partition by id2 order by id1)rn,*)t where rn<=2
[解决办法]
SQL code
--2000select *from tb twhere (select count(*) from tb where id2 = t.id2 and id1 <= t.id1) <= 2 -- 就是n 

读书人网 >SQL Server

热点推荐