Dynamic row range when calculating moving sum/average using window functions (SQL Server)

后端 未结 3 1938
礼貌的吻别
礼貌的吻别 2021-01-18 21:10

I\'m currently working on a sample script which allows me to calculate the sum of the previous two rows and the current row. However, I would like to make the number \'2\' a

3条回答
  •  隐瞒了意图╮
    2021-01-18 21:16

    You can try something like this which does not use dynamic SQL.

    DECLARE @myTable TABLE  (myValue INT)
    
    INSERT INTO @myTable ( myValue ) VALUES  ( 5)
    INSERT INTO @myTable ( myValue ) VALUES  ( 6)
    INSERT INTO @myTable ( myValue ) VALUES  ( 7)
    INSERT INTO @myTable ( myValue ) VALUES  ( 8)
    INSERT INTO @myTable ( myValue ) VALUES  ( 9)
    INSERT INTO @myTable ( myValue ) VALUES  ( 10)
    
    
    DECLARE @prev_records INT = 2
    
    ;WITH CTE as 
    (
    SELECT ROW_NUMBER() OVER(ORDER BY myValue) rn,myValue FROM @myTable
    )
    SELECT (SELECT  SUM(myValue) FROM CTE t2 WHERE t2.rn BETWEEN (t1.rn  - @prev_records) AND t1.rn )
    FROM CTE t1
    

    SUM(myValue) OVER() is best option however it does not allow you to pass previous N rows using a variable.

提交回复
热议问题