SQL Server开窗函数over()的巧用row_number(),rank(),dense_rank(),以及sum(col1) over()等

  sql server中开窗函数相比于group by用的是少,但是相对于某些功能,开窗函数却能方便简单高效的实现,个人觉得开窗函数这个名字太高雅,不能体现他的功能性,应该叫分区计算,更能体现他的本质
  函数样式: 函数名(列1) OVER(partition by 列2 order by 列3)
  具体意思就是把一个表里面的数据按照列2的层次分成一小块一小块的区域,,每个区域里面是按照列3排序的,然后在各个区域内实现按照列1的函数计算,废话不多说,上案例,下面是一个每月每天的绩效表列子。

select * from dbo.myorderdateproduction 

在这里插入图片描述

  如果我们需要查询出每个月每天的绩效按从高到低排序,则有一下三个函数可供选择,row_number(),rank(),dense_rank(),如下图所示,row_number()是业绩相同的也又先后,rank()是业绩相同的排名一样但是会跳过重叠的业绩一样的人数排名,dense_rank()是业绩相同排名一致但不会跳过重叠人数的排名,三种情况应用场景各不相同,按需使用即可。

select 
  row_number() over(partition by monthkey order by productionamount )     row_number_productionamount
 ,rank() over(partition by monthkey order by productionamount ) rank_prodmonthly
 ,DENSE_RANK()  over(partition by monthkey order by productionamount) dense_rank_prodmonthly
 ,monthkey
 ,datekey
 ,productionamount
from dbo.myorderdateproduction 
order by monthkey,productionamount

在这里插入图片描述
  另一种情况的运用,就是累计每个月截止到当天的业绩总和,平均业绩,最大业绩等等,这里以求总和为例子,就是我们经常说的MTD业绩,具体如下图所示:

在这里插入图片描述

select 
  monthkey
 ,datekey
 ,productionamount
 ,SUM(productionamount) over(partition by monthkey order by monthkey,datekey RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) productionamountMTD
 ,SUM(productionamount) over(partition by monthkey order by monthkey,datekey rows BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) productionamountMTD
 from dbo.myorderdateproduction 
 order by monthkey,datekey

结果如下:
在这里插入图片描述
其实代码中的range和rows还是有点区别的,只不过说这个列子不明显,可参考下图的一个列子,range会把相同partition和order by的值显示为一样的最终结果,但是rows不会。

  range结果:
在这里插入图片描述
  rows结果:
在这里插入图片描述
rows和range后面的常用参数如下:

UNBOUNDED PRECEDING

The window starts at the first row of the partition.

UNBOUNDED FOLLOWING

The window ends at the last row of the partition.

CURRENT ROW

window begins at the current row or ends at the current row

n PRECEDING or n FOLLOWING

The window starts or ends n rows before or after the current row

for example,

ROWS BETWEEN Unbounded preceding AND 1 Preceding

means that
the window goes from the first row of the partition to the row that stands (in
the ordered set) immediatly before the current row…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

╭⌒若隐_RowYet——大数据

谢谢小哥哥,小姐姐的巨款

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值