sql >> Base de Datos >  >> RDS >> Oracle

Seleccionar datos agrupados por hora después de la medianoche

EDITAR :Está probado ahora:SQL Fiddle

La clave es simplemente ajustar el group by para que cualquier cosa antes de las 6 am se agrupe con el día anterior. Después de eso, los conteos son bastante sencillos.

SELECT TO_CHAR(CASE WHEN EXTRACT(HOUR FROM timevalue) < 6
                    THEN timevalue - 1
                    ELSE timevalue
                    END, 'YYYY\MM\DD') AS day, 
       COUNT(*) AS overall, 
       SUM(CASE WHEN EXTRACT(HOUR FROM timevalue) >= 6 AND EXTRACT(HOUR FROM timevalue) < 14
                THEN 1 ELSE 0 END) AS morning,
       SUM(CASE WHEN EXTRACT(HOUR FROM timevalue) >= 14 AND EXTRACT(HOUR FROM timevalue) < 23
                THEN 1 ELSE 0 END) AS daytime,
       SUM(CASE WHEN EXTRACT(HOUR FROM timevalue) < 6 OR EXTRACT(HOUR FROM timevalue) >= 23
                THEN 1 ELSE 0 END) AS evening
FROM my_table
WHERE timevalue >= TO_TIMESTAMP('05.07.2015','DD.MM.YYYY')
GROUP BY TO_CHAR(CASE WHEN EXTRACT(HOUR FROM timevalue) < 6
                    THEN timevalue - 1
                    ELSE timevalue
                    END, 'YYYY\MM\DD');