日期:2014-05-18  浏览次数:20428 次

根据条件取多组前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

得到的结果为
ID1 ID2
1 1
2 1
3 2
4 3
5 3
6 3

现在假设要取多组前两条数据,希望得到的结果是
ID1 ID2
1 1
2 1
3 2
4 3
5 3

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

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

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

------解决方案--------------------
SQL code

;with AcHerat as
(
    select *,rid=row_number() over (partition by id2 order by id1)
    from tb
)

select id1,id2
from AcHerat
where 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

--2000
select *
from tb t
where (select count(*) from tb where id2 = t.id2 and id1 <= t.id1) <= 2 -- 就是n