我有一张生产表:
-------- ---------
| Items | quantity |
-------- ---------
| A | 100 |
--------------------
| B | 30 |
--------------------
| A | 10 |
--------------------
| C | 80. |
--------------------
表销售
-------- ---------
| Items | quantity |
-------- ---------
| A | 50 |
--------------------
| C | 30 |
--------------------
必填结果
-------- ---------
| Items | quantity |
-------- ---------
| A | 60 |
--------------------
| B | 30 |
--------------------
| C | 50 |
--------------------
我正在尝试使用外连接,但无法成功。请帮帮我。 感谢
答案 0 :(得分:4)
select p.items, sum(p.quantity) - coalesce(max(total_quantity), 0)
from production p
left join
(
select items, sum(quantity) as total_quantity
from sale
group by items
) s on s.items = p.items
group by p.items
答案 1 :(得分:2)
select p.Items, SUM(IFNULL(p.quantity,0))-SUM(IFNULL(s.quantity,0))
FROM production p
left join sale s
on p.items = s.items
group by p.items
编辑以防止空值。你为MySQL标记了两个不同的SQL数据库mysql和sql-server我相信它是IFNULL(如代码所示),而在sql-server中它是ISNULL