"Running Total" SQL 查询并使用自定义第一个值开始此过程
"Running Total" SQL query and starting this process with custom first value
我想用一些号码开始 "running total" 进程。
DECLARE @x int
SELECT @x = ...
@x = 50
这是我的 运行 总查询
SELECT
id, debit, credit,
SUM(debit - credit) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
FROM
TABLE
结果:
debit credit RunningTotal
--------------------------------
10 0 10
10 0 20
10 0 30
0 10 20
但是,我正在尝试从 @x
;
开始
debit credit RunningTotal
-----------------------------------
50 0 50 <--- x value (@x)
10 0 60
10 0 70
10 0 80
0 10 70
我该怎么做?
谢谢。
将虚拟行添加到具有最小 ID 的源 table:
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;
我想用一些号码开始 "running total" 进程。
DECLARE @x int
SELECT @x = ...
@x = 50
这是我的 运行 总查询
SELECT
id, debit, credit,
SUM(debit - credit) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
FROM
TABLE
结果:
debit credit RunningTotal
--------------------------------
10 0 10
10 0 20
10 0 30
0 10 20
但是,我正在尝试从 @x
;
debit credit RunningTotal
-----------------------------------
50 0 50 <--- x value (@x)
10 0 60
10 0 70
10 0 80
0 10 70
我该怎么做?
谢谢。
将虚拟行添加到具有最小 ID 的源 table:
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;