Grouping by date, with 0 when count() yields no lines

后端 未结 2 1130
温柔的废话
温柔的废话 2021-01-14 03:44

I\'m using Postgresql 9 and I\'m fighting with counting and grouping when no lines are counted.

Let\'s assume the following schema :

create table vie         


        
相关标签:
2条回答
  • 2021-01-14 04:27

    Given that you don't have the dates in the table, you need a way to generate them. You can use the generate_series function:

    SELECT * FROM generate_series('2012-01-01'::timestamp, '2012-01-07 23:00', '1 hour') AS ts;
    

    This will produce results like this:

             ts          
    ---------------------
     2012-01-01 00:00:00
     2012-01-01 01:00:00
     2012-01-01 02:00:00
     2012-01-01 03:00:00
    ...
     2012-01-07 21:00:00
     2012-01-07 22:00:00
     2012-01-07 23:00:00
    (168 rows)
    

    The remaining task is to join the two selects using an outer join like this :

    select extract ( day from ts ) as day, extract ( hour from ts ) as hour,coalesce(count,0) as count from 
    (
        SELECT  extract ( day from date ) as day , extract ( hour from date ) as hr ,count(*)
        FROM    sr
        where date>'2012-01-01' and date <'2012-01-07'
        GROUP BY   extract ( day from date ) , extract ( hour from date )
    ) AS cnt 
     right outer join ( SELECT * FROM generate_series ( '2012-01-01'::timestamp, '2012-01-07 23:00', '1 hour') AS ts ) as dtetable on extract ( hour from ts ) = cnt.hr and extract ( day from ts ) = cnt.day 
     order by day,hour asc;
    
    0 讨论(0)
  • 2021-01-14 04:29

    This query will give you the output what your are looking for,

    select to_char(date_event, 'YYYY-MM-DD HH24:00') as time, count (to_char(date_event, 'HH24:00')) as count from views where date(date_event) > '2012-01-01' and date(date_event) > '2012-01-07' group by time order by time;
    
    0 讨论(0)
提交回复
热议问题