表:
items
id | 名字 |
---|---|
1 | 螺栓 |
2 | 扳手 |
3 | 锤子 |
表:
inwards
d | item_id | 数量 |
---|---|---|
1 | 1 | 10.00 |
2 | 2 | 8.00 |
桌子
outwards
d | item_id | 数量 |
---|---|---|
1 | 1 | 5.00 |
我想要
SELECT
表格 items
第三列 AS balance
可以获取数量之间的差异 (inwards
- outwards
)
我的尝试:
SELECT it.* ,
(
(SELECT SUM(i.quantity)
FROM inwards AS i
WHERE i.item_id = it.id)
-
(SELECT SUM(o.quantity)
FROM outwards AS o
WHERE o.item_id = it.id)
) AS balance
FROM `items` AS it ORDER BY `id` ASC;
我得到的结果:
id | 名字 | 平衡 |
---|---|---|
1 | 螺栓 | 5.00 |
2 | 扳手 | 空 |
3 | 锤子 | 空 |
我的目标是:
id | 名字 | 平衡 |
---|---|---|
1 | 螺栓 | 5.00 |
2 | 扳手 | 8.00 |
3 | 锤子 | 0.00 |
with combined as (
select item_id, quantity from inwards union all
select item_id, -quantity from outwards
)
select item_id, min(name) as name, coalesce(sum(quantity), 0) as balance
from items i left outer join combined c on c.item_id = i.item_id
group by item_id;