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下使用crontab进行RMAN备份实验
    cocos2d-x 通过JNI实现c/c++和Android的java层函数互调
    整型与字符型之间转化
    MFC的最大化,最小化,关闭
    [置顶] IT屌丝的离职申请
    The Priest Mathematician
    jQuery入门学习贴
    poj3308Paratroopers(最小割)
    Nginx 开启 debug 日志的办法
    关于产品的一些思考——(四十二)网易之有道云笔记协同版
  • 原文地址:https://www.cnblogs.com/jianjialin/p/2122233.html
Copyright © 2011-2022 走看看