继续学习窗口函数Over
首先, 我们确定Sql语句执行大致流程
-
FROM =>> WHERE =>> GROUP BY =>> HAVING =>> SELECT ==>
-
{ Over
-
Distinct
-
Top} ==>
-
ORDER BY
其中比较难一点的就是Over窗口函数了.
Over单独配合聚合函数
SELECT orderid, custid, val,orderdate
,SUM(val) OVER() AS totalvalue,AVG(val) over() as avgvalueFROM Sales.OrderValues;
对比上图, 发现除了增加了两列外, 没有改变排序.SELECT orderid, custid, val,orderdate
,SUM(val) OVER() AS totalvalue,AVG(val) over() as avgvalue,SUM(val) OVER(PARTITION BY custid) AS custtotalvalue/*,AVG(val) over(PARTITION BY orderdate) as custAvgValue*/
FROM Sales.OrderValues;
对比图1. 发现, Partition By 不仅让sum聚合函数只计算CustID区域的val. 并且使得结果按custid排序SELECT orderid, custid, val,orderdate
,SUM(val) OVER() AS totalvalue,AVG(val) over() as avgvalue,SUM(val) OVER(PARTITION BY custid) AS custtotalvalue,AVG(val) over(PARTITION BY orderdate) as custAvgValueFROM Sales.OrderValues;
对比图3, 发现如果再增加一个有partitionby子句的窗口函数, 结果按照后一个(这里是orderdate)排序SELECT orderid, custid, val,orderdate,ROW_NUMBER() over(order by val desc),SUM(val) OVER() AS totalvalue,AVG(val) over() as avgvalue,SUM(val) OVER(PARTITION BY custid) AS custtotalvalue/*,AVG(val) over(PARTITION BY orderdate) as custAvgValue*/
FROM Sales.OrderValues;
结果同图4一样. 虽然增加了一列RowIndex列, 但是结果依然是按照custid排序, 除非将那一句放到后面.如果排序函数中使用了partition by子句. 那么, 返回的结果还是以partition by子句的字段升序.当然, 以上结果是在没有order by排序的前提下. 如果最外层有order by, 那么还是按order by 排序.
本人在长沙, 有工作可以加我QQ4658276