How to select SUM of previous record in group

89 views Asked by At

Question

What is the best or most expressive way to write SQL Query that selects

current row and sum of previous row withing a group

For example, given a table with columns Id, Group, Amount, how to calculate PreviousAmount

Result:

Id Group Amount PreviousAmount*
1 1 2 NULL
2 1 2 2
3 1 2 4
4 2 2 NULL

I've tried:

SELECT
    *,
    SUM(Amount) OVER (PARTITION BY Group ORDER BY ID RANGE UNBOUNDED PRECEDING) as Prev
FROM Table

but it also includes current row

2

There are 2 answers

0
SelVazi On BEST ANSWER

Here how to do it :

SELECT
    *,
    SUM(Amount) OVER (PARTITION BY [Group] ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as Prev
FROM mytable

ROWS UNBOUNDED PRECEDING means the frame's lower bound is simply infinite.

1 PRECEDING represent the row before the current row, it is the higher bound within the partition.

Demo here

2
Serg On

The simplest way is to use default range and to substract the current row amount

select *, SUM(Amount) OVER (PARTITION BY [Group] ORDER BY ID) - Amount as Prev
from tbl