ypercube的答案非常出色(我从未见过通过这样的伪选择在单个查询中创建变量),因此为方便起见,这里是CREATE TABLE语句。
对于Google Image Search中的表格数据图像,可以使用https://convertio.co/ocr/或https://ocr.space/将其转换为文本文档。然后,如果OCR无法正确检测到列,并且您使用的是Mac,请使用TextWrangler,同时按住选项键以执行矩形选择并四处移动列。SQL编辑器(例如Sequel Pro,TextWrangler)和电子表格(例如Google Docs)的结合使处理以制表符分隔的表格数据极为高效。
如果可以把所有这些都发表在评论中,那么请不要反对这个答案。
-- DROP TABLE statements;
CREATE TABLE IF NOT EXISTS statements (
id integer NOT NULL AUTO_INCREMENT,
stmnt_date date,
debit integer not null default 0,
credit integer not null default 0,
PRIMARY KEY (id)
);
INSERT INTO statements
(stmnt_date , debit, credit) VALUES
('2014-06-17', 20000, 0 ),
('2014-08-14', 0 , 3000 ),
('2014-07-16', 0 , 3000 ),
('2015-02-01', 3000 , 0 ),
('2014-05-15', 3000 , 0 );
-- this is slightly modified from ypercube's (@b := 0 vs @b := 0.0)
SELECT
s.stmnt_date, s.debit, s.credit,
@b := @b + s.debit - s.credit AS balance
FROM
(SELECT @b := 0) AS dummy
CROSS JOIN
statements AS s
ORDER BY
stmnt_date ASC;
/* result
+------------+-------+--------+---------+
| stmnt_date | debit | credit | balance |
+------------+-------+--------+---------+
| 2014-05-15 | 3000 | 0 | 3000 |
| 2014-06-17 | 20000 | 0 | 23000 |
| 2014-07-16 | 0 | 3000 | 20000 |
| 2014-08-14 | 0 | 3000 | 17000 |
| 2015-02-01 | 3000 | 0 | 20000 |
+------------+-------+--------+---------+
5 rows in set (0.00 sec)
*/