The SQL OVER() clause - when and why is it useful?

后端 未结 8 1247
有刺的猬
有刺的猬 2020-11-28 17:49
    USE AdventureWorks2008R2;
GO
SELECT SalesOrderID, ProductID, OrderQty
    ,SUM(OrderQty) OVER(PARTITION BY SalesOrderID) AS \'Total\'
    ,AVG(OrderQty) OVER(PAR         


        
8条回答
  •  情歌与酒
    2020-11-28 18:26

    The OVER clause is powerful in that you can have aggregates over different ranges ("windowing"), whether you use a GROUP BY or not

    Example: get count per SalesOrderID and count of all

    SELECT
        SalesOrderID, ProductID, OrderQty
        ,COUNT(OrderQty) AS 'Count'
        ,COUNT(*) OVER () AS 'CountAll'
    FROM Sales.SalesOrderDetail 
    WHERE
         SalesOrderID IN(43659,43664)
    GROUP BY
         SalesOrderID, ProductID, OrderQty
    

    Get different COUNTs, no GROUP BY

    SELECT
        SalesOrderID, ProductID, OrderQty
        ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'CountQtyPerOrder'
        ,COUNT(OrderQty) OVER(PARTITION BY ProductID) AS 'CountQtyPerProduct',
        ,COUNT(*) OVER () AS 'CountAllAgain'
    FROM Sales.SalesOrderDetail 
    WHERE
         SalesOrderID IN(43659,43664)
    

提交回复
热议问题