首页 > 解决方案 > 如何从同一个表中找到重叠的日期范围(多个重叠)

问题描述

有数据范围的用户数据 数据

我正在尝试使用查询来更新标志部分。如果同一用户 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

标签: sqlsql-serverdatabasetsql

解决方案


要获取'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 中获取字符串字段中重叠记录的列表要复杂得多。获得重叠的成对列表非常容易。


推荐阅读