繁体   English   中英

在 ID 条件下连接两个表,第一个表中的日期在另一个表中的其他两个日期之间

[英]Join two tables on a condition of ID and a date from first table is between two other dates in another table

我正在尝试将表 2 中与时间相关的数据添加到表 1。在表 1 中,我有 ID、日期。 在表 2 中,我有 ID、DateFrom、DateTo。 ID,日期重复。 t1 例如:

+-----+------------+------+-------+-------+
| ID  |    day     | Type | data1 | data2 |
+-----+------------+------+-------+-------+
| 111 | 21.07.2019 | -    | …     | …     |
| 111 | 01.08.2019 | -    | …     | …     |
| 111 | 14.08.2019 | -    | …     | …     |
| 112 | 21.07.2019 | -    | …     | …     |
| …   | …          |      | ..    | …     |
+-----+------------+------+-------+-------+

t2:

+-----+------------+------------+------+
| ID  | date_from  |  date_to   | Type |
+-----+------------+------------+------+
| 111 | 01.07.2019 | 03.08.2019 | AAA  |
| 111 | 04.08.2019 | 29.09.2019 | BBB  |
| 111 | 30.09.2019 | 01.12.2019 | CCC  |
| 111 | …          | …          | …    |
+-----+------------+------------+------+

我想要得到的是 - 用来自 t2 的正确数据填充Type

+-----+------------+------+-------+-------+
| ID  |    day     | Type | data1 | data2 |
+-----+------------+------+-------+-------+
| 111 | 21.07.2019 | AAA  | …     | …     |
| 111 | 01.08.2019 | AAA  | …     | …     |
| 111 | 14.08.2019 | BBB  | …     | …     |
| 112 | 21.07.2019 | BBB  | …     | …     |
| …   | …          | …    | ..    | …     |
+-----+------------+------+-------+-------+

我现在所做的:

SELECT TOP 100
t1.ID
t1.day
t2.type

FROM t1 LEFT OUTER JOIN t2 ON ( (t1.date >= t2.date_from) AND (t1.date <=t2.date_to) 
AND (t1.ID = t2.ID) )

这是正确的吗?

连接似乎是这里的相关方法。

条件周围的括号不是必需的。 您想要inner join还是left join取决于孤立记录的可能性以及您想如何处理它们: inner join删除t1中在t2没有匹配的记录,而left join允许它们(结果type将是null ):

select t1.*, t2.type
from t1
inner join t2 on t1.day between t2.date_from and t2.date_to and t2.id = t1.id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM