SQLite:运行 余额有期末余额

SQLite: Running balance with an ending balance

我的期末余额为 5000 美元。我需要创建一个 运行 余额,但调整第一行以显示期末余额,然后将其余部分相加,这样它看起来就像银行对帐单。这是 运行 余额的内容,但我如何调整第 1 行以不显示第一行的总和,而是显示期末余额。

with BalBefore as (
  select *
  from transactions
  where ACCT_NAME = 'Real Solutions'
  ORDER BY DATE DESC
)

select
  DATE,
  amount,
  '$' || printf("%.2f", sum(AMOUNT) over (order by ROW_ID)) as Balance
from BalBefore;

这给了我

DATE         AMOUNT     BALANCE
9/6/2019     -31.00     $-31.00      <- I need this balance to be replaced with 00 and have the rest
9/4/2019      15.00     $-16.00         sum as normal.
9/4/2019      15.00     $-1.00
9/3/2019     -16.00     $-17.00

我已经阅读了很多其他问题,但找不到一个我能理解的问题,所以我想 post 一个更简单的问题。

以下内容并不简短,但使用 WITH statement and CTEs,希望逻辑清晰。定义了多个 CTE,它们相互引用以使整个查询更具可读性。总的来说,目标只是添加一个开始余额记录,该记录可能是:

/*
DROP TABLE IF EXISTS data;
CREATE temp TABLE data (
       id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
       date DATETIME  NOT NULL,
       amount NUMERIC NOT NULL
);   

INSERT INTO data
(date, amount)
VALUES
     ('2019-09-03', -16.00),
     ('2019-09-04',  15.00),
     ('2019-09-04',  15.00),
     ('2019-09-06', -31.00)
;
*/

WITH 
     initial_filter AS (
         SELECT id, date, amount
         FROM data
         --WHERE ACCT_NAME = 'Real Solutions'
     ),
     prepared AS (
         SELECT *
         FROM initial_filter
         UNION ALL
         SELECT 
            9223372036854775807 as id, --largest signed integer 
            (SELECT MAX(date) FROM initial_filter) AS FinalDate, 
            -(5000.00) --ending balance (negated for summing algorithm)
     ),
     running AS (
          SELECT
                id,
                date,
                amount,
                SUM(-amount) OVER 
                    (ORDER BY date DESC, id DESC 
                     RANGE UNBOUNDED PRECEDING 
                     EXCLUDE CURRENT ROW) AS balance
          FROM prepared
          ORDER BY date DESC, id DESC
     )
SELECT *
FROM running
WHERE id != 9223372036854775807
ORDER BY date DESC, id DESC;

这会产生以下结果

id  date         amount balance
4   2019-09-06  -31.00  5000
3   2019-09-04   15.00  5031
2   2019-09-04   15.00  5016
1   2019-09-03  -16.00  5001

更新:第一个查询没有产生正确的余额。更新期初余额行和窗口函数(即 OVER 子句)以准确计算正确金额的总和。
注意:每一行的余额完全由前几行确定,而不是当前行的金额,因为这是从期末余额反向计算的, 不是从上一行余额向前。