gpt4 book ai didi

mysql - 来自不同表的求和和分组

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

我有三张 table 。

Table (Store)
+-----+-----+
| ID | Qty |
+-----+-----+
| 001 | 4 |
| 002 | 3 |
| 003 | 5 |
| 004 | 6 |
+-----+-----+

Table (Received)
+-----+-----+
| ID | Qty |
+-----+-----+
| 001 | 2 |
| 005 | 9 |
| 001 | 5 |
+-----+-----+

Table (Issued)
+-----+-----+
| ID | Qty |
+-----+-----+
| 001 | 3 |
| 003 | 2 |
| 001 | 1 |
| 005 | 2 |
+-----+-----+

我想对 (Store + Received) - Issued 中的数量求和,按 ID 分组我希望结果如下所示。请帮忙。

Table (Stock)
+-----+-----+
| ID | Qty |
+-----+-----+
| 001 | 7 |
| 002 | 3 |
| 003 | 3 |
| 004 | 6 |
| 005 | 7 |
+-----+-----+

最佳答案

你可以这样做

select 
x.id , coalesce(sum(qty),0)-coalesce(i_qty,0) from
(
select id,qty from store
union all
select id,qty from received
)x
left join(
select id,sum(qty) as i_qty
from issued group by id
)y on x.id = y.id
group by id

关于mysql - 来自不同表的求和和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469539/

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