sql >> Base de Datos >  >> RDS >> PostgreSQL

¿Cómo hacer que esta consulta también devuelva filas con 0 valor de conteo?

        -- 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
        ;