PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

como fazer essa consulta também retornar linhas com valor de contagem 0?

        -- CTE to the rescue!!!
WITH cal AS (
        SELECT generate_series('2012-02-02 00:00:00'::timestamp , '2012-03-02 05:00:00'::timestamp , '1 hour'::interval) AS stamp
        )
, qqq AS (
        SELECT date_trunc('hour', executiontime) AS stamp
        , count(*) AS zcount
        FROM mytable
        GROUP BY date_trunc('hour', executiontime)
        )
SELECT cal.stamp
        , COALESCE (qqq.zcount, 0) AS zcount
FROM cal
LEFT JOIN qqq ON cal.stamp = qqq.stamp
ORDER BY stamp ASC
        ;