记一则Oracle业务需求---获取连续日期

浏览: 2189

需求背景

获取连续的日期,比如1月31、2月1、2月2 这样连续的,跨月跨年都算作连续,如下图所示,只取标红框部分。

Clipboard Image.png

数据搭建

with ltz as
(select level as aid, trunc(sysdate - level) as bdate
from dual
connect by level <= 120),
hehe as
(select aid, bdate
from ltz
where aid in (1,2,3,5,78,7,8,9,88,100,101,102,104,106,107,108,109))
select * from hehe

思路

思路就是先关联出一个完整的表,外关联,然后获取上一条和下一条数据,取这两条都不为空且外关联后date不为空的数据

SQL

with ltz as
(select level as aid, trunc(sysdate - level) as bdate
from dual
connect by level <= 120),
hehe as
(select aid, bdate
from ltz
where aid in (1,2,3,5,78,7,8,9,88,100,101,102,104,106,107,108,109))
select aid, hbdate
from (select h.aid,
lag(h.bdate, 1, date '1970-01-01') over(order by l.bdate) as l, --get last data
h.bdate as hbdate,
lead(h.bdate, 1, date '1970-01-01') over(order by l.bdate) as bl,--get next data
l.bdate as lbdate
from hehe h, ltz l
where h.bdate(+) = l.bdate
order by 3)
where not (l is null and bl is null)
and hbdate is not null

结果

Clipboard Image.png

推荐 3
本文由 老头子 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册