有数据范围的用户数据
我正在尝试使用查询更新标记部分。如果相同的用户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
答案 0 :(得分:2)
要获取'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中获取字符串字段中的重叠记录列表要复杂得多。获得成对的重叠列表非常简单。
答案 1 :(得分:0)
您也可以将表格内部连接到自身并比较日期
SELECT *
FROM [Table] t1
INNER JOIN [Table] t2
ON t1.ID <> t2.ID
AND t1.UserId = t2.UserId
AND ((t1.RegisterDate BETWEEN t2.RegisterDate AND t2.TermDate) OR (t1.TermDate BETWEEN t2.RegisterDate AND t2.TermDate))
虽然越多的字段越来越复杂,但这就变成了
请参阅此DBFiddle