我有三张 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/