zoukankan      html  css  js  c++  java
  • 继续学习窗口函数Over

    首先, 我们确定Sql语句执行大致流程

    • FROM   =>> WHERE =>> GROUP BY =>> HAVING =>> SELECT ==>

    •             { Over

    •                Distinct

    •                Top} ==>

    • ORDER BY

    其中比较难一点的就是Over窗口函数了.

    Over单独配合聚合函数

    SELECT * FROM Sales.OrderValues;
    image有表如图1
    SELECT orderid, custid, val,orderdate
      ,SUM(val) OVER() AS totalvalue,
      AVG(val) over() as avgvalue
    FROM Sales.OrderValues;
    image图2
    对比上图, 发现除了增加了两列外, 没有改变排序.
    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;
    image图3
    对比图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 custAvgValue
    FROM Sales.OrderValues;
    image图4
    对比图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 排序.

  • 相关阅读:
    linux LTIB学习笔记
    wince WaitForMultipleObjects需要注意的问题
    微信小程序在苹果上出现[request:fail 发生了 SSL 错误无法建立与该服务器的安全连接。]错误的解决方案
    Windows 2008之PKI实战4:吊销
    十个不找工作的理由
    [zt]我奋斗了18年不是为了和你一起喝咖啡
    [zt]Java/PHP/C 几种语言 RSA 的互操作
    全职共享和兼职的一些思考pkill
    定价策略(翻译稿)
    Windows 2008之PKI实战1:管理
  • 原文地址:https://www.cnblogs.com/jianjialin/p/2122233.html
Copyright © 2011-2022 走看看