MsSql分区函数的使用

本文通过具体案例展示了如何使用SQL进行数据排名及子查询操作,包括如何获取每个员工最新的三条订单记录,以及如何找出成绩表中每班的前三名学生。

例1:根据Northwind数据库,要求查询出每个员工最近的三条订单数据

ExpandedBlockStart.gif代码
1 with result
2 as
3 (
4    select row_number()over(partition by o.employeeID order by o.orderdate desc )as row ,e.lastName,e.FirstName,o.OrderID
5    from employees e join orders o on e.employeeID=o.employeeID
6 
7 
8 select * from result where row<=
9 

select e.firstname,e.lastname,ot.* from employees e 

cross apply (select top (2) * from orders o where o.employeeID=e.employeeID order by o.orderdate desc) as ot

order by e.employeeID

 

例2: 

ExpandedBlockStart.gif代码
create table Student  --学生成绩表
(
 id 
int,  --主键
 Grade int--班级
 Score int --分数
)
insert Student  select 1,1,88
union all select 2,1,66
union all select 3,1,75
union all select 4,2,30
union all select 5,2,70
union all select 6,2,80
union all select 7,2,60
union all select 8,3,90
union all select 9,3,70
union all select 10,3,80

select * from student


select top 3 with ties * from  student order by score desc//前三名

select *,row_number() over(partition by grade order by score desc)as '名次' from student

 

 

转载于:https://www.cnblogs.com/deymmtd/archive/2010/09/17/1829532.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值