Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' as a variable. I've tried declaring a variable, or directly casting in the query, yet a syntax error always pops up. Is there a possible solution?

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)

SELECT 
    SUM(myValue) OVER (ORDER BY myValue 
                       ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
FROM @myTable
like image 270
test Avatar asked Apr 17 '15 09:04

test


People also ask

How do I select a row RANGE in SQL Server?

You can do this by using ROW_NUMBER () function provided by Sql server. your table name. It will retrieve the records from rows 10 to 20 from your table.

What is rows unbounded preceding in SQL Server?

UNBOUNDED PRECEDING – All rows before the current row. n PRECEDING – n rows before the current row. CURRENT ROW – Just the current row. n FOLLOWING – n rows after the current row. UNBOUNDED FOLLOWING – All rows after the current row.

What is RANGE between unbounded preceding and current row?

The frame, ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, means that the window consists of the first row of the partition and all the rows up to the current row. Each calculation is done over a different set of rows. For example, when performing the calculation for row 4, the rows 1 to 4 are used.

Is sum a window function in SQL?

Introduction to SQL Window Functions Similar to an aggregate function, a window function calculates on a set of rows. However, a window function does not cause rows to become grouped into a single output row. In this example, the OVER() clause signals that the SUM() function is used as a window function.


1 Answers

DECLARE @test VARCHAR = 1
DECLARE @sqlCommand VARCHAR(1000)
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)

SET @sqlCommand = 'SELECT SUM(myValue) OVER (ORDER BY myValue ROWS BETWEEN ' + @test + ' PRECEDING AND CURRENT ROW)
                  FROM #temp'

EXEC (@sqlCommand)
like image 55
Maffju Avatar answered Sep 22 '22 21:09

Maffju