This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and require output data to calculate the sum of previous values without using a self-join.
Input Data:
1 2 3 4 5 6 7 8 9 |
ID ----------- 1 2 3 4 5 6 7 |
Expected Output:
1 2 3 4 5 6 7 8 9 |
ID SumsList ----------- ----------- 1 1 2 3 3 6 4 10 5 15 6 21 7 28 |
Create a table with sample data:
1 2 3 4 5 6 |
CREATE TABLE SumOfPrev(ID INT) GO INSERT INTO SumOfPrev VALUES (1),(2),(3),(4),(5),(6),(7) GO |
Solution 1: Using SUM() OVER()
1 2 |
SELECT *, SUM(ID) OVER (ORDER BY ID) SumsList FROM SumOfPrev |
Solution 2: Using CTE
1 2 3 4 5 6 7 |
;WITH CTE AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY ID) rnk FROM SumOfPrev ) SELECT ID, SUM(ID) OVER (ORDER BY rnk) SumsList FROM CTE |
Please try the different solution for this puzzle and share it via comment...