sql – 选择按午夜时间分组的数据

我有一张桌子:

ID       TIMEVALUE
-----    -------------
1        06.07.15 06:43:01,000000000
2        06.07.15 12:17:01,000000000
3        06.07.15 18:21:01,000000000
4        06.07.15 23:56:01,000000000
5        07.07.15 04:11:01,000000000
6        07.07.15 10:47:01,000000000
7        07.07.15 12:32:01,000000000
8        07.07.15 14:47:01,000000000

我希望特殊时间对这些数据进行分组.
我当前的查询如下所示:

SELECT TO_CHAR(TIMEVALUE, 'YYYY\MM\DD'), COUNT(ID), 
  SUM(CASE WHEN TO_CHAR(TIMEVALUE, 'HH24MI') <=700 THEN 1 ELSE 0 END) as morning,
  SUM(CASE WHEN TO_CHAR(TIMEVALUE, 'HH24MI') >700 AND TO_CHAR(TIMEVALUE, 'HH24MI') <1400 THEN 1 ELSE 0 END) as daytime,
  SUM(CASE WHEN TO_CHAR(TIMEVALUE, 'HH24MI') >=1400 THEN 1 ELSE 0 END) as evening FROM Table
WHERE TIMEVALUE >= to_timestamp('05.07.2015','DD.MM.YYYY')
GROUP BY TO_CHAR(TIMEVALUE, 'YYYY\MM\DD')

我得到了这个输出

day          overall     morning    daytime    evening 
-----        ---------
2015\07\05   454         0          0          454
2015\07\06   599         113        250        236
2015\07\07   404         139        265        0

所以在同一天(0-7点,7-14点和14-24点)进行精细分组
但我现在的问题是:
我怎么能在午夜时分组?

例如,第二天的6-14,14-23和23-6点.

我希望你理解我的问题.如果有更好的解决方案,欢迎您甚至改进我的上层查询.

最佳答案 编辑:现在测试:
SQL Fiddle

关键是简单地调整组,以便在早上6点之前的任何事情与前一天分组.在那之后,计数非常简单.

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');
点赞