实现说明
这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 ledger_entries。
逐子句看,这些语句使用了:用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;必填列上的 NOT NULL 限定;补齐缺省列的 DEFAULT 值;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。
常见问题
这段 SQL 涉及哪些对象?
ledger_entries——直接引用,无需连接。
核心语句
SELECT txn_id,
SUM(debit_cents) AS total_debit,
SUM(credit_cents) AS total_credit
FROM ledger_entries
GROUP BY txn_id
HAVING SUM(debit_cents) <> SUM(credit_cents);
CREATE TABLE ledger_entries (
entry_id bigint GENERATED ALWAYS AS IDENTITY,
txn_id int NOT NULL,
account text NOT NULL,
debit_cents numeric NOT NULL DEFAULT 0,
credit_cents numeric NOT NULL DEFAULT 0
);
INSERT INTO ledger_entries (txn_id, account, debit_cents, credit_cents) VALUES
(1, 'cash', 500.00, 0),
(1, 'revenue', 0, 500.00),
(2, 'cash', 120.00, 0),
(2, 'revenue', 0, 119.99); -- 故意差一分
代码示例
-- 复式记账 (double-entry):每笔交易的平衡不变式 (invariant) 用 HAVING 检查 (check)
CREATE TABLE ledger_entries (
entry_id bigint GENERATED ALWAYS AS IDENTITY,
txn_id int NOT NULL,
account text NOT NULL,
debit_cents numeric NOT NULL DEFAULT 0,
credit_cents numeric NOT NULL DEFAULT 0
);
INSERT INTO ledger_entries (txn_id, account, debit_cents, credit_cents) VALUES
(1, 'cash', 500.00, 0),
(1, 'revenue', 0, 500.00),
(2, 'cash', 120.00, 0),
(2, 'revenue', 0, 119.99); -- 故意差一分
-- 余额视图会正常滚动,只有按笔对账才能暴露不平账
SELECT txn_id,
SUM(debit_cents) AS total_debit,
SUM(credit_cents) AS total_credit
FROM ledger_entries
GROUP BY txn_id
HAVING SUM(debit_cents) <> SUM(credit_cents);
DROP TABLE ledger_entries;