高分求解答: 利用SQL语句取每个分类的前5条记录

chineseren2000 2005-10-14 09:00:03
请问:
一个表(book)中有title字段,sort_id字段。
sort_id=1 的记录有 3条
sort_id=2 的记录有 5条
sort_id=3 的记录有 8条
sort_id=4 的记录有 10条
sort_id=5 的记录有 3条

我现在想通过一条语句,每个分类读前5条 能不能做到呢? 该怎么写?
谢谢.
...全文
386 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
chineseren2000 2005-10-14
  • 打赏
  • 举报
回复
libin_ftsafe(子陌红尘) ( **) 老兄果然是两星上将, 你的方式我测试过,KO!!! 谢谢!!
其他SQL兄的方式我也试过,上面几个用sort_id不行的,谢谢!!
散分,结贴.
下面是我在db2中的测试成功的sql,数据才15405条,比较慢
select count(*) from (
SELECT a.id,a.comcode from tbl_person a
where a.id in (
select b.id from tbl_person b
where b.comcode = a.comcode order by b.comcode fetch first 5 rows only
) order by a.comcode
) as t group by t.comcode
qianduo 2005-10-14
  • 打赏
  • 举报
回复
create table book(book_id int identity(1,1),title char(20),short_id char(20))

insert into book(title,short_id)
select 'sdfsf','1'
union select 'fghfer','1'
union select 'ooor','1'
union select 'epp','1'
union select 'e2er','1'
union select '23wer','1'
union select 'egher','1'
union select 'eyuter','5'
union select 'ejker','5'
union select 'bnrgher','2'
union select 'm,rwer','2'
union select 'm,rwgher','2'
union select 'erwer','3'
union select 'kjghwer','3'
union select 'vcvgher','3'
union select 'nbghwer','3'
union select 'ryghg','3'
union select 'yuy','4'

select b.* from book b where book_id in
(select top 5 book_id from book where short_id =b.short_id)

drop table book
rivery 2005-10-14
  • 打赏
  • 举报
回复
楼主可以把表的字段信息全列出来,这样有助于得到高效、可靠的代码。
前5条是按照什么来确定的?主键?时间字段?
Alang_79 2005-10-14
  • 打赏
  • 举报
回复
select * from book a
where exists ( select top 5 sort_id from book where sort_id=a.sort_id )
子陌红尘 2005-10-14
  • 打赏
  • 举报
回复
如果相同sort_id对应的记录中title内容不重复:

select
a.*
from
book a
where
a.title in(select top 5 title from book where sort_id=a.sort_id)
chineseren2000 2005-10-14
  • 打赏
  • 举报
回复
谢谢各位光临, 我这里的sort_id 字段的值不定死的,可能有1,2,3,5, 也可能有1 2 3 4 5 6 7 8
lxzm1001 2005-10-14
  • 打赏
  • 举报
回复
select * from book t where id in(select top 5 id from book where book.id=t.id)
zlp321002 2005-10-14
  • 打赏
  • 举报
回复
--try
select a.* from 表 a
where sort_id in ( select top 5 sort_id from 表 where sort_id=a.sort_id )
tangqijun199 2005-10-14
  • 打赏
  • 举报
回复
select top 5 * from book where sort_id=1 union select top 5 * from book where sort_id=2 union select top 5 * from book where sort_id=3 union select top 5 * from book where sort_id=4 union select top 5 * from book where sort_id=5

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧