♣
请教一个分组排序的问题?
有表结构如下
id , content(内容) ,sort(类别)
1 aaa 0
2 bbb 3
3 ccc 1
4 ddd 3
5 ddd 1
6 rtre 3
7 dsdf 3
8 dsdf 0
....
想要得到如下结果集:
id , content(内容) ,sort(类别)
sort 为0的一个组
1 aaaa 0
8 dsdf 0
sort 为1的一个组
3 ccc 1
5 ddd 1
sort 为3的一个组
2 bbb 3
4 ddd 3
6 rtre 3
7 dsdf 3
如上所示要按sort来排序分组,每组最多4条记录,每组中又按id来排序
如何写sql语句?
· 网友精彩回答:
select * from test1 as a where id in
(select 4 id from test1 c where c.sort =
(select sort from test1 b where a.sort = b.sort and a.sort=c.sort group by sort ))
order by a.sort,a.id
一个很垃圾的写法
--try
create table test(id int identity(1,1) ,content char(8),sort int )
insert into test select aaa,0
union all select bbb, 3
union all select ccc, 1
union all select ddd, 3
union all select ddd, 1
union all select rtre, 3
union all select dsdf, 3
union all select dsdf, 0
select id,content,sort from test
group by sort,content,id
having count(*)<=4
order by sort,id
--
id content sort
----------- -------- -----------
1 aaa 0
8 dsdf 0
3 ccc 1
5 ddd 1
2 bbb 3
4 ddd 3
6 rtre 3
7 dsdf 3
select * from 表 a
where id in(
select top 4 id from 表 where [sort]=a.[sort] order by id)
order by [sort],id
select * from 表 a where (select count(1) from 表 where [sort]=a.[sort] and id<=a.id)<=4 order by [sort],id
.- 更多问题:
- · 怎样给datagrid控件加一个自动增加的序号列?
- · asp.net用户控件有无开发工具?
- · 请问同一个word文件下如何生成两个目录?
- · 哪位给小弟发个verycd注册码,在下愿以一gmail注册号相还!
- · 因无人回,再发一贴:看看我的存贮过程哪句错了,有关临时表的。(可读性应该不差)
- · 源程序怎样在.net 2003下运行?看到效果?
- · [求助]关于用dispose释放内存的问题
- · 配ODBC
- · DWORD nByteswritten(0);这个什么意思?
- · UDP数据包大小问题?
- · 比如我的IP是60.176.32.36,那我在IE地址栏里输入//60.176.32.36,怎么跳出来一个对话框要我输入用户名和密码,到底咋回事?
- · 找socketserver原码
- · 比较难的问题:Eclipse和重构高手进
- · 在提交了一次add后,选择列表中的中文都变成了"????????",为什么?
- · 100分求解UDP控件的奇怪问题,解决就给分。
- · 关于PB中英文翻译的文章(2天类结帖)(前天的帖子刚结帖了)

