gpt4 book ai didi

具有相同 ID 的 MySQL SUM

转载 作者:可可西里 更新时间:2023-11-01 08:20:57 26 4
gpt4 key购买 nike

对于真正简单的问题,我很抱歉,我刚刚学习 PHP 和 MySQL,我已经用谷歌搜索了一个多星期,但我没有找到任何答案。

我创建了一个简单的财务脚本,表格如下所示:

table_a
aid | value
1 | 100
2 | 50
3 | 150

table_b
bid | aid | value
1 | 1 | 10
2 | 1 | 15
3 | 2 | 5
4 | 2 | 10
5 | 3 | 25
6 | 3 | 40

我想要这样的结果

No | ID | Total | Balance
1 | 1 | 10 | 90
2 | 1 | 25 | 75
3 | 2 | 5 | 45
4 | 2 | 15 | 35
5 | 3 | 25 | 125
6 | 3 | 65 | 85

谁能帮我解决我的问题?

谢谢

最佳答案

试试这个累计总数:http://www.sqlfiddle.com/#!2/ce765/1

select  
bid as no, value,
@rt := if(aid = @last_id, @rt + value, value) as total,
@last_id := aid
from table_b b, (select @rt := 0 as x, @last_id := null) as vars
order by b.bid, b.aid;

输出:

| NO | VALUE | TOTAL | @LAST_ID := AID |
|----|-------|-------|-----------------|
| 1 | 10 | 10 | 1 |
| 2 | 15 | 25 | 1 |
| 3 | 5 | 5 | 2 |
| 4 | 10 | 15 | 2 |
| 5 | 25 | 25 | 3 |
| 6 | 40 | 65 | 3 |

然后join表A,最终查询:

select x.no, x.aid, x.value, x.total, a.value - x.total as balance
from
(
select
bid as no, aid, value,
@rt := if(aid = @last_id, @rt + value, value) as total,
@last_id := aid
from table_b b, (select @rt := 0 as x, @last_id := null) as vars
order by b.bid, b.aid
) as x
join table_a a using(aid)

输出:

| NO | AID | VALUE | TOTAL | BALANCE |
|----|-----|-------|-------|---------|
| 1 | 1 | 10 | 10 | 90 |
| 2 | 1 | 15 | 25 | 75 |
| 3 | 2 | 5 | 5 | 45 |
| 4 | 2 | 10 | 15 | 35 |
| 5 | 3 | 25 | 25 | 125 |
| 6 | 3 | 40 | 65 | 85 |

现场测试:http://www.sqlfiddle.com/#!2/ce765/1


更新

不依赖列bid 排序,分组运行总计不会受到影响:http://www.sqlfiddle.com/#!2/6a1e6/3

select x.no, x.aid, x.value, x.total, a.value - x.total as balance
from
(
select
@rn := @rn + 1 as no, aid, value,
@rt := if(aid = @last_id, @rt + value, value) as total,
@last_id := aid
from table_b b, (select @rt := 0 as x, @last_id := null, @rn := 0) as vars
order by b.aid, b.bid
) as x
join table_a a using(aid)

输出:

| NO | AID | VALUE | TOTAL | BALANCE |
|----|-----|-------|-------|---------|
| 1 | 1 | 10 | 10 | 90 |
| 2 | 1 | 15 | 25 | 75 |
| 3 | 1 | 7 | 32 | 68 |
| 4 | 2 | 5 | 5 | 45 |
| 5 | 2 | 10 | 15 | 35 |
| 6 | 3 | 25 | 25 | 125 |
| 7 | 3 | 40 | 65 | 85 |

现场测试:http://www.sqlfiddle.com/#!2/6a1e6/3

关于具有相同 ID 的 MySQL SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10869407/

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