sql - 如何从同一个表中找到重叠的日期范围(多个重叠)
问题描述
有数据范围的用户数据
我正在尝试使用查询来更新标志部分。如果同一用户 id 组与任何单日范围重叠,则应在标志部分显示重叠。
你能给我一些想法如何标记这个重叠数据吗谢谢
Text file format:
ID UserID registereddate termdate flag
1 abcd 1/1/2018 2/28/2018 overlapping with 2
2 abcd 1/1/2018 6/30/2018 overlapping with 1
3 abcd 8/1/2018 12/31/2018
4 bbbb 5/1/2018 6/30/2018 overlapping with 5
5 bbbb 6/1/2018 7/30/2018 overlapping with 4
6 bbbb 9/1/2018 9/30/2018
7 bbbb 10/1/2018 10/30/2018
8 bbbb 11/1/2018 11/30/2018
9 ccccc 7/1/2018 9/30/2018 overlapping with 10
10 ccccc 9/1/2018 12/31/2018 overlapping with 9
11 dddd 8/1/2018 8/31/2018
12 dddd 12/1/2018 12/31/2018
13 eeee 9/1/2018 12/31/2018 overlapping with 17
14 eeee 8/1/2018 8/31/2018
15 eeee 9/1/2018 9/30/2018 overlapping with 15
解决方案
要获取'overlapping'
,请使用exists
:
select t.*,
(case when exists (select 1
from t t2
where t2.registereddate < t.termdate and
t2.termdate > t.registereddate
)
then 'overlaps'
end)
from t;
在更新中,这看起来像:
update t
set flag = 'overlaps'
where exists (select 1
from t t2
where t2.registereddate < t.termdate and
t2.termdate > t.registereddate
);
在 SQL Server 中获取字符串字段中重叠记录的列表要复杂得多。获得重叠的成对列表非常容易。
推荐阅读
- react-native - 可以在 React Native 库中加载 .XIB 或 Storyboard 吗?
- python - MacO 上的证书验证失败
- angular - 在 nativescript angular 中,component.ts 和 html 上的变量的双重绑定在某些页面中不起作用。(虽然仅在登录页面中工作)
- angular - Angular 7 Reactive Form Builder,自定义交叉验证器不起作用
- python - Keras网络训练速度下降
- cordova - ionic 3 Location Accuracy Get Error Object(...) 不是函数
- javascript - 使用正则表达式重命名对象数组的键
- java - 字节码中的内部 kotlin 修饰符是什么?
- c++ - 如何正确使用矩阵进行数学运算以进行 opengl 转换?
- android - RecyclerView 在项目插入时显示错误的元素