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

按分类字段值取特定记录的前两条
觉得表达得也不太正确,具体如下表:
id       分类
1           a
2           b
3           c
4           b
5           b
6           a
7           c
8           a
9           c
要取出记录(1、6)(2、4)(3、7),就是分类字段中等于a、b、c的记录的前两条,想找一个灵巧的方法。

------解决方案--------------------
create table T(id int, type varchar(10))
insert T select 1, 'a '
union all select 2, 'b '
union all select 3, 'c '
union all select 4, 'b '
union all select 5, 'b '
union all select 6, 'a '
union all select 7, 'c '
union all select 8, 'a '
union all select 9, 'c '

select * from T as tmp
where (select count(*) from T where type=tmp.type and id <tmp.id) <2
order by type

--result
id type
----------- ----------
1 a
6 a
2 b
4 b
3 c
7 c

(6 row(s) affected)

------解决方案--------------------
create table #t(id int identity,type char(1))

insert #t select 'a '
union all select 'b '
union all select 'c '
union all select 'b '
union all select 'b '
union all select 'a '
union all select 'c '
union all select 'a '
union all select 'c '

--执行结果
select t.*
from #t t,
(select type,max(id) Id
from #t
group by type) s
where t.type = s.type
and t.id < s.id