查询数据的最大排序问题(只能用一条语句写)
2008-01-17 16:28
519 查看
CREATE TABLE hard (qu char (11) ,co char (11) ,je numeric(3, 0))
insert into hard values ('A','1',3)
insert into hard values ('A','2',4)
insert into hard values ('A','4',2)
insert into hard values ('A','6',9)
insert into hard values ('B','1',4)
insert into hard values ('B','2',5)
insert into hard values ('B','3',6)
insert into hard values ('C','3',4)
insert into hard values ('C','6',7)
insert into hard values ('C','2',3)
要求查询出来的结果如下:
qu co je
----------- ----------- -----
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4
就是要按qu分组,每组中取je最大的前2位!!
而且只能用一句sql语句!!!
select * from hard a where (select count(*) from hard b
where a.qu=b.qu and b.je>=a.je)<=2
ORDER BY qu,je DESC
选出一条记录, 然后做循环.
这么写会好懂一些?
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je)
可以这样写:
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je desc)
insert into hard values ('A','1',3)
insert into hard values ('A','2',4)
insert into hard values ('A','4',2)
insert into hard values ('A','6',9)
insert into hard values ('B','1',4)
insert into hard values ('B','2',5)
insert into hard values ('B','3',6)
insert into hard values ('C','3',4)
insert into hard values ('C','6',7)
insert into hard values ('C','2',3)
要求查询出来的结果如下:
qu co je
----------- ----------- -----
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4
就是要按qu分组,每组中取je最大的前2位!!
而且只能用一句sql语句!!!
select * from hard a where (select count(*) from hard b
where a.qu=b.qu and b.je>=a.je)<=2
ORDER BY qu,je DESC
选出一条记录, 然后做循环.
这么写会好懂一些?
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je)
可以这样写:
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je desc)
相关文章推荐
- SQL学习之查询技巧 查询第3的数据 用一条语句分组,排序 并查询某一排名
- 现在有这样一个问题 我把上W条数据插入表内,但是发现还有一条数据没进入表里.我想查出来是哪个数据没进去. 能用查询语句查出来吗?
- SQL学习之查询技巧 查询第3的数据 用一条语句分组,排序 并查询某一排名
- SQL反模式学习笔记18 减少SQL查询数据,避免使用一条SQL语句解决复杂问题
- android中Sqlite查询的数据返回排序问题
- mysql查询获取分组后最新的一条记录,策略:先排序,然后在次分组查询(默认第一条),就是最新的一条数据了
- Oracle分页查询排序数据重复问题
- 在myeclipse6.5 中运行main函数测试webservice服务端利用hql语句查询数据库里的数据的时候的问题
- Oracle学习之路(一):oracle简介+基本sql语句+条件查询+排序数据理论与案例
- 有一组数据3,5,9,7,4,13,15,0,2,20.已知最大数是20,把数据从小到大排序,而且算法复杂度只能是1
- [MySQL]学习笔记- 用户行为表中,查询每个人的一条最新行为(分组 排序 取时间最大的一条记录)
- sql语句 用户一天的数据,取最大的一条,再统计
- 【Excle】在重复数据中对日期排序并查询最新的一条记录
- SqlServer 基础知识 数据检索、查询排序语句
- 自己发现的nodejs服务的问题--1查询语句的嵌套问题+接受的数据该怎么用
- 一条SQL语句实现查询每个部门中年龄最大的员工信息
- Select查询数据放一个内表,然后在下一条select语句用where语句in 该内表
- Oracle 删除重复数据只留一条 查询及删除重复记录的SQL语句 1、查找表中多余的重复记录,重复记录是根据单个字段(Id)来判断 select * from 表 wher
- Sql Server exists 查询相同姓名或编号 年份最大的一条数据
- SQL语句中查询并在结果中添加一条虚拟数据