你真的会玩SQL吗?冷落的Top和Apply
作者:网络转载 发布时间:[ 2015/12/8 11:44:14 ] 推荐标签:数据库
练习:
从学生表中选取对应班级的前num名学生成绩
--显示结果
/*
bj xh name cj
---------- ---- ---------- -----------
一班 A006 A6 100
一班 A005 A5 99
一班 A001 A1 89
一班 A002 A2 89
二班 B001 B7 100
二班 B001 B6 99
二班 B001 B9 97
二班 B001 B8 90
二班 B001 B5 88
*/
-- 创建测试表
declare @student table(
---学生表
bj varchar(10),
-- 班级
xh char(4),
-- 学号
name varchar(10),
-- 姓名
cj int)
-- 成绩
declare @tj table(
---统计表
bj varchar(10),
-- 班级
num int)
-- 人数 :从学生表中选取对应班级的前num名学生成绩
set nocount on
-- 添加测试数据
insert @student select '一班' ,'A001','A1',89
insert @student select '一班' ,'A002','A2',89
insert @student select '一班' ,'A003','A3',59
insert @student select '一班' ,'A004','A4',80
insert @student select '一班' ,'A005','A5',99
insert @student select '一班' ,'A006','A6',100
insert @student select '一班' ,'A007','A7',82
insert @student select '二班' ,'B001','B1',19
insert @student select '二班' ,'B001','B2',81
insert @student select '二班' ,'B001','B3',69
insert @student select '二班' ,'B001','B4',86
insert @student select '二班' ,'B001','B5',88
insert @student select '二班' ,'B001','B6',99
insert @student select '二班' ,'B001','B7',100
insert @student select '二班' ,'B001','B8',90
insert @student select '二班' ,'B001','B9',97
insert @tj select '一班',3
insert @tj select '二班',5
参考SQL:
-- 2005.T-SQL
select t.bj,s.xh,s.name,s.cj
from @tj t
cross apply (
SELECT TOP(t.num)
with ties
-- 加 with ties,一班将选出4个人(2个人并列第三名)
xh,name,cj
from @student
where t.bj=bj
-- 加where 功能类似于 inner join ;不加类似于 cross join
order by cj desc
)s
order by case when t.bj='一班' then 1 else 2 end asc,s.cj desc,s.xh asc
---排序
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。

sales@spasvo.com