34,587
社区成员
发帖
与我相关
我的任务
分享
create table tb(id int,name varchar(10))
insert into tb
select 1,'a1' union all
select 2,'a1' union all
select 3,'a1' union all
select 4,'a1' union all
select 5,'a2' union all
select 6,'a2' union all
select 7,'a3'
select id,name
from tb a
where (select count(1) as num from tb where name=a.name and id<=a.id)<4
/*
id name
---------------
1 a1
2 a1
3 a1
5 a2
6 a2
7 a3
*/
drop table tb
--> 测试数据: #
if object_id('tempdb.dbo.#') is not null drop table #
create table # (id int,name varchar(2))
insert into #
select 1,'a1' union all
select 2,'a1' union all
select 3,'a1' union all
select 4,'a1' union all
select 5,'a2' union all
select 6,'a2' union all
select 7,'a3'
select * from # a where id in (select top 3 id from # where name = a.name order by 1)
/*
id name
1 a1
2 a1
3 a1
5 a2
6 a2
7 a3
*/