Regarding db fiddle
Table: items
| id | name |
|---|---|
| 1 | bolt |
| 2 | wrench |
| 3 | hammer |
Table: inwards
| id | item_id | quantity |
|---|---|---|
| 1 | 1 | 10.00 |
| 2 | 2 | 8.00 |
Table outwards
| id | item_id | quantity |
|---|---|---|
| 1 | 1 | 5.00 |
I want to SELECT table items with a third column AS balance which gets the difference between quantities (inwards - outwards)
My attempt:
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;
The result I get:
| id | name | balance |
|---|---|---|
| 1 | bolt | 5.00 |
| 2 | wrench | null |
| 3 | hammer | null |
What I am aiming to get:
| id | name | balance |
|---|---|---|
| 1 | bolt | 5.00 |
| 2 | wrench | 8.00 |
| 3 | hammer | 0.00 |
You could have
coalesce()ed your two sums which would prevent the nulls in the output. Check into null propagation to understand why that was happening. This can be fixed inside the subquery ascoalesce(sum(quantity), 0)You might also consider this approach which might give you better flexibility overall if other data columns become relevant: