当前位置: 数据库>sqlserver
sql server分组查询与排序的例子
来源: 互联网 发布时间:2014-08-29
本文导语: 有这样一张表: 代码示例: create table topic ( Topicid int, title nvarchar(10), boardid int, addtime datetime ) 数据如下: 代码示例: insert topic select 1, 'abc', 100, '2007-1-1' union all select 2, 'era',...
有这样一张表:
代码示例:
create table topic
(
Topicid int,
title nvarchar(10),
boardid int,
addtime datetime
)
(
Topicid int,
title nvarchar(10),
boardid int,
addtime datetime
)
数据如下:
代码示例:
insert topic select
1, 'abc', 100, '2007-1-1'
union all select 2, 'era', 101, '2007-1-2'
union all select 3, 'avx', 102, '2007-1-3'
union all select 4, 'zcv', 100, '2007-1-4'
union all select 5, 'jhv', 100, '2007-1-5'
union all select 6, 'ztw', 103, '2007-1-6'
union all select 7, 'xcv', 102, '2007-1-7'
union all select 8, 'zww', 104, '2007-1-8'
union all select 9, 'zqw', 105, '2007-1-9'
union all select 10, 'zti', 103, '2007-1-10'
1, 'abc', 100, '2007-1-1'
union all select 2, 'era', 101, '2007-1-2'
union all select 3, 'avx', 102, '2007-1-3'
union all select 4, 'zcv', 100, '2007-1-4'
union all select 5, 'jhv', 100, '2007-1-5'
union all select 6, 'ztw', 103, '2007-1-6'
union all select 7, 'xcv', 102, '2007-1-7'
union all select 8, 'zww', 104, '2007-1-8'
union all select 9, 'zqw', 105, '2007-1-9'
union all select 10, 'zti', 103, '2007-1-10'
要求,按照boardid分组,按照datetime排序,取出前五条。
sql语句:
代码示例:
select top 5 boardid from
(
select boardid,max(addtime) as addtime
from topic
group by boardid
) tmp order by addtime desc
(
select boardid,max(addtime) as addtime
from topic
group by boardid
) tmp order by addtime desc
解释:
1,group by 和 order by 不能同时使用,所以当要分组后再排序的时候就要嵌套(先分好组再排序)
2,但是在group by的时候,你要查询的字段必须是你分组的字段,如果group by 两个字段,分组时是按照两个字段同时相等的分组,因此达不到自己想要的结果。
但是使用一个字段分组,要查到两个字段就得:
代码示例:
select boardid,max(addtime) as addtime
from topic
group by boardid
from topic
group by boardid
3,最后把分组后的结果在排序:因为在分组查询时没有查出addtime字段就没办法order by addtime desc。
在日常的开发中,sql server中用于分组查询与排序的需求还是很多的,建议大家好好掌握下这块内容。