我有两张表,我想加入日期范围。表1如下所示:
Table 1:
----------------------------------------------------------------------------------
| ID | Place | Description | Date 1 | Date 2 |
----------------------------------------------------------------------------------
| 1 | Place 1 | Description 1 | 1/1/1988 | 12/31/1993 |
----------------------------------------------------------------------------------
| 2 | Place 1 | Description 2 | 1/1/1994 | 12/31/1994 |
----------------------------------------------------------------------------------
| 3 | Place 1 | Description 3 | 1/1/1995 | 2/8/2018 |
----------------------------------------------------------------------------------
表2如下所示:
Table 2:
---------------------------------------------------------------------------------
| ID | Equipment | Place | Date 1 | Date 2 |
---------------------------------------------------------------------------------
| 1 | Item 1 | Place 1 | 1/1/1990 | 12/31/1995 |
---------------------------------------------------------------------------------
| 2 | Item 2 | Place 1 | 1/1/1996 | 2/8/2018 |
---------------------------------------------------------------------------------
我希望结果如下:
Results:
------------------------------------------------------------------------------------------
| Equipment | Place | Description | Date 1 | Date 2 |
------------------------------------------------------------------------------------------
| Item 1 | Place 1 | Description 1 | 1/1/1990 | 12/31/1993 |
------------------------------------------------------------------------------------------
| Item 1 | Place 1 | Description 2 | 1/1/1994 | 12/31/1994 |
------------------------------------------------------------------------------------------
| Item 1 | Place 1 | Description 3 | 1/1/1995 | 12/31/1995 |
------------------------------------------------------------------------------------------
| Item 2 | Place 1 | Description 3 | 1/1/1996 | 2/8/2018 |
------------------------------------------------------------------------------------------
在上面的示例中,我基本上尝试将“描述”添加到表2.但是,表1中的“描述”与表2中的记录集没有相同的日期范围。
我正在努力想出一个查询,甚至是一组查询来生成所需的结果。任何推动都是正确的方向,非常感谢。
答案 0 :(得分:1)
您将需要一个主要从表2中获取的查询,然后对表1执行具有多个条件的双向连接。第一个连接将到位, 第二个连接也需要加入日期范围:
粗糙的SQL将是(免责声明:未经测试):
SELECT
T2.[Description], T2.[Place], T1.[Description], etc..
FROM
T2
INNER JOIN T1 ON
T1.[Place] = T2.[Place]
AND
(
T2.[Date 1] BETWEEN T1.[Date 1] AND T1.[Date 2]
AND
T2.[Date 2] BETWEEN T1.[Date 1] AND T1.[Date 2]
)