if object_id('pubs..tb') is not null
drop table tb
go
create table tb(ID int,Type varchar(10),name varchar(10))
insert into tb(ID,Type,name) values(1,'狗','吉娃娃')
insert into tb(ID,Type,name) values(2,'狗','藏獒')
insert into tb(ID,Type,name) values(3,'狗','哈斯其')
insert into tb(ID,Type,name) values(4,'猫','波斯猫')
insert into tb(ID,Type,name) values(5,'猫','白猫')
insert into tb(ID,Type,name) values(6,'猫','黑猫')
insert into tb(ID,Type,name) values(7,'兔','黄兔')
insert into tb(ID,Type,name) values(8,'兔','白兔')
insert into tb(ID,Type,name) values(9,'兔','黑兔')
select * from tb t
where name in
(
select top 2 name from tb where type=t.type order by name
)
drop table tb
/*
ID Type name
----------- ---------- ----------
2 狗 藏獒
3 狗 哈斯其
4 猫 波斯猫
5 猫 白猫
8 兔 白兔
9 兔 黑兔
declare @t table( id int ,type varchar(10), name varchar(10))
insert into @t select 1,'狗','吉娃娃'
union all select 2,'狗','藏獒'
union all select 3,'狗','哈斯其'
union all select 4,'猫','波斯猫'
union all select 5,'猫','白猫'
union all select 6,'猫','黑猫'
union all select 7,'兔','黄兔'
union all select 8,'兔','白兔'
union all select 9,'兔','黑兔'
select * from @t a where id in (select top 2 id from @t where type=a.type order by id )
/*
id type name
----------- ---------- ----------
1 狗 吉娃娃
2 狗 藏獒
4 猫 波斯猫
5 猫 白猫
7 兔 黄兔
8 兔 白兔