Home  >  Article  >  Database  >  Oracle 合并连续时间段

Oracle 合并连续时间段

WBOY
WBOYOriginal
2016-06-07 17:27:501809browse

给出几个时间点,合并Oracle连续的时间点。例如:09:00-10:00,10:00-12:00,12:00-16:00 合并输出为09:00-16:0009:00-10:00,10:00

给出几个时间点,合并Oracle连续的时间点。
例如:
09:00-10:00,10:00-12:00,12:00-16:00 合并输出为09:00-16:00
09:00-10:00,10:00-12:00,12:00-16:00 ,17:00-18:00 输出为09:00-16:00 ,17:00-18:00
09:00-10:00,10:00-12:00,12:00-16:00 ,17:00-18:00,18:00-20:00 输出为 09:00-16:00 ,17:00-20:00

如下是使用lag,lead函数实现:
lag(column,N,defValue):取上一条记录
参数:column 取某列的值
N 取几条,默认取1条
defValue:如果没有取到值,返回该默认值。【比如取第一条的上一条,是取不到值的,如果给了该参数,则返回
该值,,否则为null】
lead(column,N,defValue):取下一条记录


SQL语句如下:
select start_time,lead(priv,1,end_time) over(order by start_time) end_time from (
select start_time,end_time,(start_time-lag(end_time,1,1)over(order by start_time)) diff,
lag(end_time,1,1)over(order by end_time) priv
from (
select replace(substr(a,1,instr(a,'-',1,1)-1),':','') start_time,
replace(substr(a,instr(a,'-',-1,1)+1),':','') end_time
from (
select '09:00-10:00' a from dual union
select '10:00-11:00' a from dual union
select '11:00-12:00' a from dual union
select '13:00-14:00' a from dual union
select '15:00-16:00' a from dual union
select '17:00-18:00' a from dual union
select '18:00-20:00' a from dual union
select '20:00-21:00' a from dual union
select '21:00-22:00' a from dual union
select '23:00-24:00' a from dual union
select '25:00-26:00' a from dual ---这句是额外添加上,当然值只要不在24小时内就行,为了算法需要
)
)
) where diff0 and start_time'2500'; --2500是25:00的转换值,这里我们需要去掉'25:00-26:00'这条记录

执行结果如下:

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn