I have a table of date-based items, many of which have gaps between months and years. For example, if a post has been created in January, and five in April, I'll have gaps in Feb, March, May, and June. I've been scouring around and found that one thing to do is to use a numbers table, or create a temporary months table, and join off of that, but I still can't seem to get it to work. Here's what I have so far:
CREATE OR REPLACE TABLE temp_months (id INT unsigned PRIMARY KEY);
INSERT INTO temp_months
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12);
SELECT
COUNT(p.ID) AS COUNT,
YEAR(p.created_date) as YEAR,
tm.id as MONTH
FROM
temp_months tm
LEFT OUTER JOIN
my_table p
ON
MONTH(p.created_date) = tm.id
WHERE
p.company_id = 123456
GROUP BY
MONTH, YEAR
ORDER BY
p.created_date DESC
This gives me the following format, with gaps (almost like I didn't join it to the temp table at all)
+-------+------+-------+
| COUNT | YEAR | MONTH |
+-------+------+-------+
| 1 | 2020 | 5 |
| 3 | 2020 | 2 |
| 1 | 2020 | 1 |
| 9 | 2019 | 10 |
| 2 | 2019 | 8 |
+-------+------+-------+
What I would like it to do, is fill in the gaps with an empty/null/0 COUNT
, like:
+-------+------+-------+
| COUNT | YEAR | MONTH |
+-------+------+-------+
| NULL | 2020 | 6 |
| 1 | 2020 | 5 |
| NULL | 2020 | 4 |
| NULL | 2020 | 3 |
| 3 | 2020 | 2 |
| 1 | 2020 | 1 |
| NULL | 2019 | 12 |
| NULL | 2019 | 11 |
| 9 | 2019 | 10 |
| NULL | 2019 | 9 |
| 2 | 2019 | 8 |
| NULL | 2019 | 7 |
+-------+------+-------+
I'm just not quite sure where I'm messing up.