sql - SQL - 根据日期差异选择行
问题描述
假设我们有下表:
代码 | DT |
---|---|
c1 | 2020-10-01 |
c1 | 2020-10-05 |
c1 | 2020-10-09 |
c1 | 2020-10-10 |
c1 | 2020-10-20 |
c2 | 2020-10-07 |
c2 | 2020-10-09 |
c2 | 2020-10-15 |
c2 | 2020-10-16 |
c2 | 2020-10-20 |
c2 | 2020-10-24 |
Code和Dt的组合是独一无二的。根据 Code 和 Dt 对行进行排序。数据库是 Oracle 12。对于每个代码,我想获取其 Dts 列表,与之前选择的 Dt 相比,每个 Dt 大于 7 天。因此,结果应该是:
代码 | DT |
---|---|
c1 | 2020-10-01 |
c1 | 2020-10-09 |
c1 | 2020-10-20 |
c2 | 2020-10-07 |
c2 | 2020-10-15 |
c2 | 2020-10-24 |
如果日期差大于 7,我已经尝试基于 row_number() 将每一行与其前一行连接起来。但是存在一个挑战,即每一行都应该与先前选择的行进行比较,而不是与表中的前一行进行比较。有什么解决办法吗?谢谢
解决方案
您可以使用match_recognize相对轻松地解决这个问题
with data(code, dt) as (
select 'c1', to_date('2020-10-01', 'YYYY-MM-DD') from dual union all
select 'c1', to_date('2020-10-05', 'YYYY-MM-DD') from dual union all
select 'c1', to_date('2020-10-09', 'YYYY-MM-DD') from dual union all
select 'c1', to_date('2020-10-10', 'YYYY-MM-DD') from dual union all
select 'c1', to_date('2020-10-20', 'YYYY-MM-DD') from dual union all
select 'c2', to_date('2020-10-07', 'YYYY-MM-DD') from dual union all
select 'c2', to_date('2020-10-09', 'YYYY-MM-DD') from dual union all
select 'c2', to_date('2020-10-15', 'YYYY-MM-DD') from dual union all
select 'c2', to_date('2020-10-16', 'YYYY-MM-DD') from dual union all
select 'c2', to_date('2020-10-20', 'YYYY-MM-DD') from dual union all
select 'c2', to_date('2020-10-24', 'YYYY-MM-DD') from dual
)
select *
from data match_recognize (
partition by code
order by dt
measures
init.dt dt
one row per match
pattern (init less_than_7_days*)
define
less_than_7_days as less_than_7_days.dt - init.dt < 7
)
您只需按代码分区,按日期排序,然后获取日期差小于 7的任何行init
和 0 多个后续行 ( )(与 init 相比)。less_than_7_days*
您为整个匹配(init + 以下行)返回 1 行,其中将包含从init
推荐阅读
- laravel - Laravel:将 order by 与 whereHas 结合使用
- firebase - CocoaPods 找不到 pod“Firebase/CoreOnly”的兼容版本:React native firebase
- vue.js - Yarn 通过代理安装包 - 网络问题
- android - 如何在 Espresso 测试中重新启动 Android 应用程序?
- kubernetes - Kubernetes资源请求相对于节点资源
- python - pybind11 通过引用访问私有类成员
- c# - 如何在 AngleSharp 中使用“过滤器”方法?
- typescript - TypeScript:如何推断赋值的确切类型
- exception - 救援如何进一步提出或忘记异常
- javascript - 如何在反应中使用三元运算符渲染条件jsx?