Search code examples
sqlstored-proceduressql-server-2014cumulative-sum

"Running Total" SQL query and starting this process with custom first value


I want to start "running total" process with some number.

DECLARE @x int
SELECT @x = ...
@x = 50

This is my running total query

SELECT 
    id, debit, credit,
    SUM(debit - credit) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
FROM 
    TABLE

and result:

debit    credit     RunningTotal
--------------------------------
10       0          10
10       0          20
10       0          30
0        10         20

But, I'm trying start with @x;

debit      credit     RunningTotal
-----------------------------------
50         0          50            <--- x value (@x)
10         0          60
10         0          70
10         0          80
0          10         70

How can I do this?

Thank you.


Solution

  • Add dummy row to the source table with smallest id:

    SELECT  debit, credit,
    SUM(debit - credit) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
    FROM 
    (select id, debit, credit from tab 
    union all 
    select -1 as id, @x as debit, 0 as credit) tab;