基本上t1看起来像这样
DATE Profile PCS
1/2/2019 DIE6660 8
1/2/2019 DIE9240 9
2/2/2019 DIE9240 7
2/2/2019 DIT8990 1
2/2/2019 DIT6690 5
3/2/2019 DIE6770 2
4/2/2019 DIE9240 6
而且t2看起来像这样
DATE Profile CON
1/2/2019 DIE9240 B
2/2/2019 DIE9240 B
2/2/2019 DIT6690 B
3/2/2019 DIE6770 N
4/2/2019 DIE9240 N
所以我想加入这些表,但必须是t2 ID与t1 ID之前的最后一个日期相连
所以基本上t2中“4/2/2019”中的“DIE9240”必须与t1中“2/2/2019”中的“DIE9240”连接。它不能与“4/2/2019”中的那个连接,因为它是相同的日期(不是它之前),也不是“1/2/2019”,因为它不是它之前的最后一个日期。
反正有吗?非常感激
这是我尝试过的,如sql视图中所示
SELECT *
FROM t1 INNER JOIN t2
ON
t2.profile = t1.profile
and
t1.date = (select max(date) from t1 where profile = t2.profile and date
< t2.date)
Query1:从每个配置文件组的上一个记录中提取日期。
SELECT (SELECT TOP 1 Dupe.date FROM t1 AS Dupe
WHERE Dupe.profile = t1.profile AND Dupe.date < t1.date ORDER BY Dupe.date DESC) AS PD, *
FROM t1;
Query2:使用复合连接将Query1连接到t2。根据所需的输出,加入Query1.PD和t2.Date字段或Query1.Date和t2.Date字段。
SELECT Query2.Date, Query2.PD, Query2.Profile, Query2.PCS, t2.CON
FROM t2 INNER JOIN Query2 ON (t2.Date = Query2.PD) AND (t2.Profile = Query2.Profile);