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

后端 未结 8 1250
有刺的猬
有刺的猬 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:15

    Let me explain with an example and you would be able to see how it works.

    Assuming you have the following table DIM_EQUIPMENT:

    VIN         MAKE    MODEL   YEAR    COLOR
    -----------------------------------------
    1234ASDF    Ford    Taurus  2008    White
    1234JKLM    Chevy   Truck   2005    Green
    5678ASDF    Ford    Mustang 2008    Yellow
    

    Run below SQL

    SELECT VIN,
      MAKE,
      MODEL,
      YEAR,
      COLOR ,
      COUNT(*) OVER (PARTITION BY YEAR) AS COUNT2
    FROM DIM_EQUIPMENT
    

    The result would be as below

    VIN         MAKE    MODEL   YEAR    COLOR     COUNT2
     ----------------------------------------------  
    1234JKLM    Chevy   Truck   2005    Green     1
    5678ASDF    Ford    Mustang 2008    Yellow    2
    1234ASDF    Ford    Taurus  2008    White     2
    

    See what happened.

    You are able to count without Group By on YEAR and Match with ROW.

    Another Interesting WAY to get same result if as below using WITH Clause, WITH works as in-line VIEW and can simplify the query especially complex ones, which is not the case here though since I am just trying to show usage

     WITH EQ AS
      ( SELECT YEAR AS YEAR2, COUNT(*) AS COUNT2 FROM DIM_EQUIPMENT GROUP BY YEAR
      )
    SELECT VIN,
      MAKE,
      MODEL,
      YEAR,
      COLOR,
      COUNT2
    FROM DIM_EQUIPMENT,
      EQ
    WHERE EQ.YEAR2=DIM_EQUIPMENT.YEAR;
    

提交回复
热议问题