我想以月为单位选择天数,然后按天数划分四个时间范围

时间:2018-06-27 18:53:34

标签: sql oracle plsql

问题在于范围“ THREE”,从晚上10点到第二天早上6点,结果是前一天,我有这个查询给我错误的数据报告, 请提供任何解决方案。

select TRUNC (A.time)+06/24,
       count (distinct B.code)as FOUR,
       count(case when to_char(A.time,'HH24:MI:SS') between '06:00:00'
                                                        and '14:00:00'
                  then A.sn end) as ONE,
       count(case when to_char(A.time,'HH24:MI:SS') between '14:00:00'
                                                        and '22:00:00'
                  then A.sn end) as TWO,
       count(case when A.time between TO_DATE ('10:00:00 PM', 'hh:mi:ss AM')
                                  and TO_DATE ('10:00:00 PM', 'hh:mi:ss AM')+6/24
                  then A.sn end) as THREE
from   B
inner join A
  on B.bol_id = A.bol_id
where  B.group = '9'
and    A.time between '01-JUN-18 06:00:00' and '25-JUN-18 06:00:00'
GROUP BY TRUNC (A.time)

我希望结构像这样example

1 个答案:

答案 0 :(得分:0)

您的问题出在GROUP BY TRUNC (A.time)上-这表示要在午夜开始每一行/每天的窗口,并在第二天晚上11:59结束。但是您想要从当天的早上6点到第二天的5:59。因此,您想GROUP BY TRUNC(A.time - 6/24)-这样,今天上午5:59将被视为昨天,明天5:59将被视为今天。

然后,您可以将案例THREE修改为:

count(case when to_char(A.time,'HH24:MI:SS') > '22:00:00'
             or to_char(A.time,'HH24:MI:SS') < '06:00:00'
           then A.sn end) as THREE

尝试一下,让我们知道您是否有任何问题。

select TRUNC(A.time-(6/24)),
       count (distinct B.code)as FOUR,
       count(case when to_char(A.time,'HH24:MI:SS') between '06:00:00'
                                                        and '14:00:00'
                  then A.sn end) as ONE,
       count(case when to_char(A.time,'HH24:MI:SS') between '14:00:00'
                                                        and '22:00:00'
                  then A.sn end) as TWO,
       count(case when to_char(A.time,'HH24:MI:SS') > '22:00:00'
                     or to_char(A.time,'HH24:MI:SS') < '06:00:00'
                   then A.sn end) as THREE
from   B
inner join A
  on B.bol_id = A.bol_id
where  B.group = '9'
and    A.time between '01-JUN-18 06:00:00' and '25-JUN-18 06:00:00'
GROUP BY TRUNC(A.time-(6/24))

您可能还希望将案例从between更改为> and <=between X and Y包含两个最终值,因此恰好在下午2点发生的任何事件都将被重复计为ONE和TWO。