Oracle,将持续时间多行划分为一小时

时间:2018-07-25 00:44:07

标签: sql oracle

我知道这里回答了这个问题:

Oracle, split a time duration row by one hour period

但是,如果您有多个这样的时间段怎么办: enter image description here

我有以下查询:

select AdmitDate, PatientName, Room, greatest(start_time, trunc(start_time+(level-1)/24, 'hh24')) beginTime, least(end_time, trunc(start_time+(level)/24, 'hh24')) endTime
from Utilization
connect by level <= floor((trunc(end_time, 'hh')-trunc(start_time, 'hh'))*24)+1 

,但返回的结果似乎不正确。 enter image description here

如果我只有一个时间行表,那么效果很好。

有没有一种方法可以按PatientName或仅分开计算的每一行对结果进行分组?

1 个答案:

答案 0 :(得分:1)

您真的非常亲密。添加DISTINCT和ORDER BY,我认为您已经找到了想要的结果:

SELECT DISTINCT AdmitDate,
                PatientName,
                Room,
                greatest(start_time, trunc(start_time+(level-1)/24, 'hh24')) beginTime,
                least(end_time, trunc(start_time+(level)/24, 'hh24')) endTime
  from Utilization
  connect by level <= floor((trunc(end_time, 'hh')-trunc(start_time, 'hh'))*24)+1
  ORDER BY 1, 2, 3, 4, 5

这将产生:

ADMITDATE               PATIENTNAME ROOM BEGINTIME              ENDTIME
2012-01-24 00:00:00     Patient1    RM1  2012-01-24 07:30:00    2012-01-24 08:00:00
2012-01-24 00:00:00     Patient1    RM1  2012-01-24 08:00:00    2012-01-24 08:32:00
2012-01-24 00:00:00     Patient2    RM1  2012-01-24 08:45:00    2012-01-24 09:00:00
2012-01-24 00:00:00     Patient2    RM1  2012-01-24 09:00:00    2012-01-24 09:13:00

SQLFiddle here