简体   繁体   中英

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

I'm trying to add to table 1 time-related data from table 2. In table 1 I have ID, date. In table 2 I have ID, DateFrom, DateTo. IDs, dates repeating. t1 for example:

+-----+------------+------+-------+-------+
| 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 | …          | …          | …    |
+-----+------------+------------+------+

What I want to get - is to fill Type with proper data from t2:

+-----+------------+------+-------+-------+
| 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  | …     | …     |
| …   | …          | …    | ..    | …     |
+-----+------------+------+-------+-------+

What I have done for now:

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) )

Is it correct?

A join seems the relevant approach here.

The parentheses around conditions are not necessary. Whether you want an inner join or a left join depends on the possibility of orphan records and how you want to handle them: inner join removes records in t1 that have no match in t2 , while left join s allows them (the resulting type will be 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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