怎样提出每组的前五个记录,如果该组记录少于5个,则有多少记录显示多少记录
比如数据格式 如下:
dept title
001 x01
001 x02
001 x03
001 x04
001 x05
001 x06
001 x07
002 x21
002 x22
003 x31
003 x32
003 x33
003 x34
003 x35
003 x36
003 x37
==================
求 怎样实现 查询的列表如下结果
dept title
001 x01
001 x02
001 x03
001 x04
001 x05
002 x21
002 x22
003 x31
003 x32
003 x33
003 x34
003 x35
======================
语句怎么写啊
select * from tablename a where title in (select top 5 tilte from tablename where a.dept=dept )
select * from 表名 where title in (select top 5 title from 表名 where dept in (select distinct dept from 表名))
select * from tablename a where
title in (select top 5 title from tablename where dept=a.dept order by title )
create table #temp(dept char(4),title char(4))
insert into #temp(dept,title) values(001,x01)
insert into #temp(dept,title) values(001,x02)
insert into #temp(dept,title) values(001,x03)
insert into #temp(dept,title) values(001,x04)
insert into #temp(dept,title) values(001,x05)
insert into #temp(dept,title) values(001,x06)
insert into #temp(dept,title) values(001,x07)
insert into #temp(dept,title) values(002,x21)
insert into #temp(dept,title) values(002,x22)
insert into #temp(dept,title) values(003,x31)
insert into #temp(dept,title) values(003,x32)
insert into #temp(dept,title) values(003,x33)
insert into #temp(dept,title) values(003,x34)
insert into #temp(dept,title) values(003,x35)
insert into #temp(dept,title) values(003,x36)
insert into #temp(dept,title) values(003,x37)
select * from #temp a where title in (select top 5 title from #temp where a.dept = dept order by title )
drop table #temp;
sdhdy(大江东去...)、tj_dns(愉快的登山者)结果正解.
dept title
---- -----
001 x01
001 x02
001 x03
001 x04
001 x05
002 x21
002 x22
003 x31
003 x32
003 x33
003 x34
003 x35
我发现大家都不喜欢用游标阿,是不是因为效率太低,而且比较复杂
select * from 你的表 a where title in (select top 5 title from 你的表 where dept=a.dept)
用游标+臨時表(如果字段很多)
游标效率太低,也不能利用索引,数据多的时候速度明显地慢:
所以,能够不用游标,就不要用.
游标效率太低,也不能利用索引,数据多的时候速度明显地慢:
所以,能够不用游标,就不要用.