根据时间和日期对值求和

时间:2018-12-26 00:06:07

标签: sql oracle

我需要添加日期的不同时间间隔读取值的帮助。

假设一天中有24小时,我希望连续四小时到八点,另一行分别是0-4pm和9pm,这是一整天。

我正在使用以下查询:

SELECT
 ennt_date,
 CASE
  WHEN to_number(TO_CHAR(dta.end_time,'HH24:MI:SS'),'sssss')/60 >= 960
  AND  to_number(TO_CHAR(dta.end_time,'HH24:MI:SS'),'sssss') /60 <= 
 1200
 THEN   (reads)
 ELSE   (reads)
 END 
from MD_data
group by ennt_date 

出现错误提示:

  

案例未按功能分组

3 个答案:

答案 0 :(得分:1)

这应该有效。您可以根据需要调整hhGroup时间范围。我不清楚4 pm-8pm是通过7:59(8pm)还是8:59(9pm)

SELECT ennt_date
       ,hhGroup
       ,Count(1) as cnt
FROM   
    (Select 
        ennt_date
        ,CAST( dta.end_time as time) as tm
        ,DATEPART(HH, dta.end_time ) as hh
        ,CASE When DATEPART(HH, dta.end_time ) < 16 Then '0am-4pm'
              When DATEPART(HH, dta.end_time ) < 20 Then '4pm-8pm'
              When DATEPART(HH, dta.end_time ) < 21 Then '8pm-9pm'
              When DATEPART(HH, dta.end_time ) < 24 Then '9pm-mid'
         END as hhGroup
     From md_data
    ) as mm
GROUP  BY ennt_date, hhGroup 

答案 1 :(得分:0)

您可以将一天划分为4小时,然后分别将每一天相加:

with
x as (
  select
    (extract(hour from end_time) div 4) * 4 as fragment,
    reads
  from md_data
)
select
  fragment,
  sum(reads)
from x
group fragment

答案 2 :(得分:0)

示例结果会有所帮助,但我想您想要

SELECT trunc(ennt_date),
       ( ceil( extract(hour from ennt_date) / 4.0) * 4 - 4 ) as hour,
       SUM(reads)
from MD_data
group by trunc(ennt_date),
         ceil( extract(hour from ennt_date) / 4.0);