我想从mysql
计算余额200
270
295
285
270
250
我尝试但不工作
SELECT `id`, `in`, `out`,balance
FROM (SELECT t.*,
@n := IF(@g <> id, 0, @n) + COALESCE(in,0) - COALESCE(out, 0) balance,
@g := id
FROM product_trans t,
(SELECT @n := 0) n,
(SELECT @g := 0) g ORDER BY id ) q
答案 0 :(得分:0)
SELECT t1.id, SUM(t2.`in` - t2.`out`) AS balance
FROM tab t1
JOIN tab t2
ON t2.id <= t1.id
GROUP BY t1.id
ORDER BY t1.id;
的 SqlFiddleDemo
强>
输出:
╔═════╦═════════╗
║ id ║ balance ║
╠═════╬═════════╣
║ 1 ║ 200 ║
║ 2 ║ 270 ║
║ 3 ║ 295 ║
║ 4 ║ 285 ║
║ 5 ║ 270 ║
║ 6 ║ 250 ║
╚═════╩═════════╝
答案 1 :(得分:0)
您还可以使用变量来计算运行总和:
小提琴: http://sqlfiddle.com/#!9/edf9d/3/0
conf
在除MySQL之外的大多数数据库中,例如Oracle或SQL Server,您将使用分析函数。