34,594
社区成员
发帖
与我相关
我的任务
分享
create table tb (col1 varchar(10),col2 int)
insert into tb select 'aa' ,1
insert into tb select 'aa', 2
insert into tb select 'aa', 3
insert into tb select 'bb', 11
insert into tb select 'bb', 21
insert into tb select 'bb', 31
insert into tb select 'bb', 41
insert into tb select 'bb', 51
insert into tb select 'cc', 12
insert into tb select 'cc', 22
insert into tb select 'cc', 32
select * from tb T where col2 in
(select top 2 col2 from tb where col1 = T.col1 group by col2 order by col2)
drop table tb
/*
col1 col2
aa 1
aa 2
bb 11
bb 21
cc 12
cc 22
*/
/*
-- Author:Flystone
-- Version:V1.001 Date:2008-05-15 初稿
-- Version:V1.002 Date:2008-05-16 1、 处理空格带来的异常
-- 2、 增加了形如yyyy-mm-dd hh:mm:ss
-- yyyy-m-d h:m:s 格式的处理
*/
-- Test Data: ta
If object_id('ta') is not null
Drop table ta
Go
Create table ta(字段一 varchar(2),字段二 int)
Go
Insert into ta
select 'aa',1 union all
select 'aa',2 union all
select 'aa',3 union all
select 'bb',11 union all
select 'bb',21 union all
select 'bb',31 union all
select 'bb',41 union all
select 'bb',51 union all
select 'cc',12 union all
select 'cc',22 union all
select 'cc',32
Go
--Start
select *
from ta a
where 字段二 in (select top 2 字段二 from ta where a.字段一 = 字段一 order by 字段二)
--Result:
/*
字段一 字段二
---- -----------
aa 1
aa 2
bb 11
bb 21
cc 12
cc 22
(所影响的行数为 6 行)
*/
--End
DECLARE @a TABLE(a varchar(10),b int)
INSERT @a SELECT 'aa', 1
union all select 'aa', 2
union all select 'aa', 3
union all select 'bb', 11
union all select 'bb', 21
union all select 'bb', 31
union all select 'bb', 41
union all select 'bb', 51
union all select 'cc', 12
union all select 'cc', 22
union all select 'cc', 32
SELECT * FROM @a a WHERE b IN(SELECT TOP 2 b FROM @a WHERE a=a.a)
--result
/*
a b
---------- -----------
aa 1
aa 2
bb 11
bb 21
cc 12
cc 22
(所影响的行数为 6 行)
*/