时间重复算法

本文介绍了一种使用SQL处理时间区间的复杂案例,通过构建临时表来管理不同时间段及其重叠情况,实现了对时间区间的精确管理和计算。适用于需要精细化管理时间数据的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

with tt as(select 1 id, to_date('8:00 ','hh24:mi')starttime,   to_date(' 10:00','hh24:mi')endtime,    2 h,    0 mi from dual union all 
    select 2 id, to_date('8:10 ','hh24:mi')starttime,   to_date(' 9:10 ','hh24:mi')endtime,   1  h,   00 mi from dual union all 
    select 3 id, to_date('09:00','hh24:mi')starttime,   to_date('10:10','hh24:mi')endtime,  1   h,  10  mi from dual union all 
    select 4 id, to_date('09:00','hh24:mi')starttime,   to_date('11:50 ','hh24:mi')endtime,   2  h,   50 mi from dual union all 
    select 5 id, to_date('12:00','hh24:mi')starttime,   to_date('13:00 ','hh24:mi')endtime,   1  h,   0  mi from dual union all 
    select 6 id, to_date('14:00','hh24:mi')starttime,   to_date('16:00 ','hh24:mi')endtime,   2  h,   0  mi from dual union all 
    select 7 id, to_date('15:00','hh24:mi')starttime,   to_date('16:00 ','hh24:mi')endtime,   1  h,   0  mi from dual )
      
,t1 as (select tt.*,row_number()over(order by starttime,endtime) rn from tt)
select id,starttime,endtime,h,mi,
  case when time is not null then (case when time>=1 then trunc(time)||'小时' end)||(case when mod(time,1)>0 then round(mod(time,1)*60)||'分钟' end)||'/4小时'
    else (case when h>0 then h||'小时' end)||(case when mi>0 then mi||'分钟' end)end 结果
from(
  
  select id,starttime,endtime,h,mi,case when not(h+mi/60=max(h+mi/60)over(partition by flag)) then 
     sum(h+mi/60)over(partition by flag)-max(h+mi/60)over(partition by flag) end time from(
       
    select a.*,connect_by_root rn flag,level from  t1 a
    start with not exists(select from t1 where rn=a.rn-1 and endtime>=a.starttime)
  connect by starttime<=prior endtime and prior rn=rn-1
  )
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值