Join a count query on a generate_series in postgres and also retrieve Null-values as “0”

蹲街弑〆低调 提交于 2019-12-01 15:55:07

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!