Postgresql group month wise with missing values

后端 未结 3 666
无人共我
无人共我 2020-12-21 06:34

first an example of my table:

id_object;time;value;status
1;2014-05-22 09:30:00;1234;1
1;2014-05-22 09:31:00;2341;2
1;2014-05-22 09:32:00;1234;1
...
1;2014-0         


        
3条回答
  •  鱼传尺愫
    2020-12-21 06:35

    you can use generate_series() function like this:

    select
        g.month,
        count(m)
    from generate_series(1, 12) as g(month)
        left outer join my_table as m on
            m.id_object = 1 and
            m.status = 1 and
            extract(year from m.time) = 2014 and
            extract(month from m.time) = g.month
    group by g.month
    order by g.month
    

    sql fiddle demo

提交回复
热议问题