What I want to get is a statistic with each month from a generate_series and the sum of the counted id\'s in every month. This SQL works in PostgreSQL 9.1:
Untangled, simplified and fixed, it might look like this:
SELECT to_char(s.tag,'yyyy-mm') AS monat
, count(t.id) AS eintraege
FROM (
SELECT generate_series(min(date_from)::date
, max(date_from)::date
, interval '1 day'
)::date AS tag
FROM mytable t
) s
LEFT JOIN mytable t ON t.date_from::date = s.tag AND t.version = 1
GROUP BY 1
ORDER BY 1;
db<>fiddle here
Among all the noise, misleading identifiers and unconventional format the actual problem was hidden here:
WHERE version = 1
While you made correct use of RIGHT [OUTER] JOIN
, you voided the effort by adding a WHERE
clause that requires a distinct value from mytable
- converting the RIGHT JOIN
to a JOIN
effectively.
Pull the clause down into the JOIN
condition to make this work.
I simplified some other things.
Related: