根据重叠的时间间隔加入表

时间:2017-09-20 09:47:42

标签: sql join

我有两个表,其中包含指定日期间隔的记录。这些表有两个共同的字段。间隔字段表示为两个表中使用的两个字段(从/到)。我想根据常见字段和重叠间隔加入它们:

Joining two tables with diff intervals

我该怎么做?我想要表1中的所有记录,当表2中的间隔重叠时,我希望在结果中添加该记录。

2 个答案:

答案 0 :(得分:0)

您可以使用具有表示日期重叠的条件的外部联接:

select    t1.*, 
          t2.depth_from as from2, t2.depth_to as to2, t2.code as code2
from      table1 t1
left join table2 t2
       on t1.DataSet = t2.DataSet
      and t1.HoleID = t2.HoleID
      and t1.Depth_From < t2.Depth_To 
      and t1.Depth_To > t2.Depth_From

答案 1 :(得分:0)

将表格加入两个公共字段,然后将结果限制为只有深度范围完全或部分重叠的记录。您没有指定正在使用的RDBMS,因此您可能需要相应地进行修改。

SELECT 
      t1.* 
    , t2.Depth_From AS DFrom
    , t2.Depth_To AS DTo
    , t2.Code AS Code
FROM
    table1 AS t1
    LEFT JOIN table2 AS t2
        ON t1.DataSet = t2.DataSet
            AND t1.HoleID = t2.HoleID
WHERE 
       (t1.Depth_From <= t2.Depth_From AND t1.Depth_To >= t2.Depth_To)
    OR (t1.Depth_From >= t2.Depth_From AND t1.Depth_To <= t2.Depth_To)
    OR (t1.Depth_From < t2.Depth_From AND t1.Depth_To > t2.Depth_From)
    OR (t1.Depth_From < t2.Depth_To AND t1.Depth_To > t2.Depth_To);