SQL 以日期间隔合并两个表

问题描述 投票:0回答:1

我有 2 个带有开始日期和结束日期的表。 我必须以特定的方式加入:

表A:

身份证 开始日期 结束日期
1 2024年1月1日 2024年10月1日
1 2024年10月1日 2024年1月15日
1 2024年1月15日 2024年1月20日

表B:

身份证 开始日期 结束日期
1 2024年10月1日 11/01/2024
1 2024年12月1日 2024年1月18日

输出:

身份证 开始日期 (A) 结束日期 (A) 开始日期(B) 结束日期(B)
1 2024年1月1日 2024年10月1日
1 2024年10月1日 2024年1月15日 2024年10月1日 11/01/2024
1 2024年10月1日 2024年1月15日 2024年12月1日 2024年1月18日
1 2024年1月15日 2024年1月20日

你能找到带有

WHERE
条件的正确 SQL 查询来获得所需的输出吗?不使用
RANK
ROW_NUMBER

sql date intervals dateinterval
1个回答
0
投票

这是使用 LEFT JOIN 的解决方案。

如果 TableB 中没有匹配的行,我们仍然包含 TableA 中 StartDate_B 和 EndDate_B 值为 NULL 的行。

SELECT 
    A.ID,
    A.StartDate AS StartDate_A,
    A.EndDate AS EndDate_A,
    B.StartDate AS StartDate_B,
    B.EndDate AS EndDate_B
FROM 
    TableA A
LEFT JOIN 
    TableB B ON A.ID = B.ID
            AND (
                (B.StartDate >= A.StartDate AND B.StartDate < A.EndDate) OR
                (B.EndDate > A.StartDate AND B.EndDate <= A.EndDate) OR
                (B.StartDate <= A.StartDate AND B.EndDate >= A.EndDate)
            )
WHERE
    B.ID IS NOT NULL
    OR (B.ID IS NULL AND A.ID IS NOT NULL);
© www.soinside.com 2019 - 2024. All rights reserved.