分组查询与排序
2008-05-13 09:49
357 查看
有一张表如下:
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', 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排序,取出前五条
语句:
select top 5 boardid from
(
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
3,最后把分组后的结果在排序:因为在分组查询时没有查出addtime字段就没办法order by addtime desc
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', 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排序,取出前五条
语句:
select top 5 boardid from
(
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
3,最后把分组后的结果在排序:因为在分组查询时没有查出addtime字段就没办法order by addtime desc
相关文章推荐
- SQL 特殊查询实例 分组、编号、排序、行号
- 先分组查询,然后为每组数据排序,取出最大值
- 【Oracle】day04_子查询_分页查询_DECODE_排序_集合操作_高级分组
- 2.数据检索|模糊查询|数据排序|数据分组| 常见问题0726
- 【原创】StreamInsight查询系列(八)——基本查询操作之分组排序
- oracle 根据某个字段分组,再根据另一个字段排序的sql查询 即 组内排序
- Sql Server -partition by 使用说明 -分组排序-分组并查询其他字段
- 实验五 SQL查询(排序、集函数和分组子句的应用)
- 父子分组的数据进行排序:一般试用于多维查询
- SQL学习之查询技巧 查询第3的数据 用一条语句分组,排序 并查询某一排名
- LINQ排序,join on,分组查询,any和all量词
- 实验三(2) SQL查询(排序、集函数和分组子句的应用)
- SQL 特殊查询实例 分组、编号、排序、行号(咋个办呢 zgbn)
- mysql分组查询排序
- 关于Lucene分组查询后的排序
- hibernate--HQL查询语句-----分组、排序--多条件排序
- mysql分组排序查询
- SQLSever 第二堂课,主要学习内容为top查询前多少行,distinct去重,order by排序,group by分组,最重要子查询
- 数据库原理之查询排序,分组和汇总(二)(第15天)
- ORACLE使用row_number() over(...)对查询数据进行分组并排序