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

后端 未结 1 1477
野趣味
野趣味 2020-12-19 00:48

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:



        
相关标签:
1条回答
  • 2020-12-19 01:15

    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:

    • Generating time series between two dates in PostgreSQL
    0 讨论(0)
提交回复
热议问题