gpt4 book ai didi

mysql - 有没有办法在 mysql View 中计算余额?

转载 作者:行者123 更新时间:2023-11-30 22:33:00 25 4
gpt4 key购买 nike

enter image description here

我想从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

最佳答案

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 ║
╚═════╩═════════╝

关于mysql - 有没有办法在 mysql View 中计算余额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com