学习 APPLY 和 TOP 用法

-- 学习 APPLY 和 TOP 用法

-----------------------------------------------------------------------
--
SQL 版本:
--
-----------
--
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)
--
    Oct 14 2005 00:33:37
--
    Copyright (c) 1988-2005 Microsoft Corporation
--
    Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
---------------------------------------------------------------------

--> 创建测试表
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

-- 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    ---排序


/*
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
*/
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值