日期:2014-05-17  浏览次数:20694 次

高人,指点下 SQL分组、排名查询
本帖最后由 snlx200808 于 2014-01-04 15:59:40 编辑
用这个语句:
select * from tb a where 2>=(select count(*) from tb where a.专业=专业 and a.部门=部门 and a.成绩>成绩)
实现不了下面两个功能,请求各分指点一下。。。。


------解决方案--------------------
先建个表:

--drop table tb


create table tb(
id int,姓名 varchar(10),
专业 varchar(10) ,
部门  varchar(10),成绩 int
)

insert into tb
select 1,'a1','通信','生产第一部',98 union all
select 2,'a2','通信','生产第一部',98 union all
select 3,'a3','通信','生产第一部',99 union all
select 4,'a4','通信','生产第一部',67 union all
select 5,'a5','信号','生产第一部',56 union all
select 6,'a6','信号','生产第一部',55 union all
select 7,'a7','信号','生产第二部',66 union all
select 8,'a8','信号','生产第二部',78 union all
select 9,'a9','信号','生产第二部',98 union all
select 10,'a10','信号','生产第三部',76 union all
select 11,'a11','供电','生产第三部',55 union all
select 12,'a12','供电','生产第三部',45 union all
select 13,'a13','供电','生产第三部',67 
go


查询:

--1.
select id ,姓名,专业,部门,成绩
from 
(
select *,
       dense_rank() over(partition by 部门 order by 成绩 desc) rownum
from tb 
)a
where rownum <= 2
order by id
/*
id 姓名 专业 部门 成绩
1 a1 通信 生产第一部 98
2 a2 通信 生产第一部 98
3 a3 通信 生产第一部 99
8 a8 信号 生产第二部 78
9 a9 信号 生产第二部 98
10 a10 信号 生产第三部 76
13 a13 供电 生产第三部 67
*/


--2.
select id ,姓名,专业,部门,成绩
from 
(
select *,
       dense_rank() over(partition by 专业 order by 成绩 desc) rownum
from tb 
)a
where rownum <= 2
order by id
/*
id 姓名 专业 部门 成绩
1 a1 通信 生产第一部 98
2 a2 通信 生产第一部 98
3 a3 通信 生产第一部 99
8 a8 信号 生产第二部 78
9 a9 信号 生产第二部 98
11 a11 供电 生产第三部 55
13 a13 供电 生产第三部 67
*/