I have a simple calendar year monthly data set returned but I know I will have missing months (i.e. no data).
I found this answer here:
Best way to count records by arbitrary time intervals in Rails+Postgres
It's close but I do not understand the JOIN USING
syntax.
I have my side figured out for the most part:
SELECT TO_CHAR(activity_tasks.start_date, 'MON') AS month,
EXTRACT(MONTH FROM activity_tasks.start_date) AS month_num,
SUM(cost_planned) FILTER (WHERE activity_tasks.aasm_state IN ('open', 'planned' ) ) AS planned,
SUM(cost_actual) FILTER (WHERE activity_tasks.aasm_state IN ('closed' ) ) AS actual
FROM "activity_tasks"
WHERE activity_tasks.start_date >= '2020-01-01' AND activity_tasks.start_date <= '2020-12-31'
GROUP BY month, month_num
ORDER BY month_num
Which gets me:
+-------+-----------+---------+--------+
| month | month_num | planned | actual |
+-------+-----------+---------+--------+
| NOV | 11 | NULL | 123 |
| DEC | 12 | 500 | NULL |
+-------+-----------+---------+--------+
I just want to join:
SELECT *
FROM (
SELECT to_char(m, 'MON') AS mmm
FROM generate_series('2020-01-01', '2020-12-31', interval '1 month') m
) m
in to one simple expression and have a full JAN-DEC dataset including the empty months.
Bonus Side Question: is there a more elegant SQL to build the generate_series('2020-01-01', '2020-12-31', interval '1 month')
array of months and set my WHERE activity_tasks.start_date >= '2020-01-01' AND activity_tasks.start_date <= '2020-12-31'
? In my case the default is Jan 1 of a given year BUT there may be a case where the accounting fiscal year is some other month and looking to avoid duplicate logic here and perhaps just feed in a single start date.