MYSQL: returning zero when no value is present, categorized monthly
-
20-09-2019 - |
Question
I have the following two tables that record expenditure and provide expenditure category information:
Table transactions:
+-------+--------+--------+
| month | cat_id | amount |
+-------+--------+--------+
| 1 | 2 | 3 |
| 1 | 2 | 8 |
| 2 | 1 | 7 |
| 2 | 1 | 5 |
+-------+--------+--------+
Table categories:
+--------+-------------+
| cat_id | cat_desc |
+--------+-------------+
| 1 | Stock |
| 2 | Consumables |
+--------+-------------+
What I would like is to construct a query that displays a sum of the amounts for each category, for each month, even if there is no expenditure in that category for that month like this:
+-------+-------------+--------+
| month | cat_desc | amount |
+-------+-------------+--------+
| 1 | Stock | 0 |
| 1 | Consumables | 11 |
| 2 | Stock | 12 |
| 2 | Consumables | 0 |
+-------+-------------+--------+
I suspect an outer join would need to be used but I haven't found a statement to do it yet.
Thank you for any help.
Solution
This one should provide you with the correct result. The inner select prepares a list of all months combined with all categories, and the LEFT JOIN
handles the rest.
SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount
FROM (
SELECT DISTINCT t.month, c.cat_id, c.cat_desc
FROM categories c
CROSS JOIN transactions t
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
Performance might be better with the following (using DISTINCT
only where necessary), but you will have to try:
SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount FROM (
SELECT t.month, c.cat_id, c.cat_desc
FROM
(SELECT DISTINCT month FROM transactions) t
CROSS JOIN categories c
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
OTHER TIPS
SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)
FROM categories c
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY c.cat_id,t.month
SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)
FROM categories c
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY t.month,c.cat_id
Order By t.month