我有两张桌子,一张是顾客与同事交谈的时间,另一张是他们购买的时间,但我不知道如何将最近的购买与某位同事联系起来。
例如
表1-同事互动
[ColleagueID] [DateOfInteraction] [CustomerID]
------------------------------------------------
A 2018-11-22 12:00 123
B 2018-11-22 12:02 123表2-采购清单
[PurchaseID] [DateOfPurchase] [PurchaseOutcome] [CustomerID]
----------------------------------------------------------------
1 2018-11-22 12:01 FAIL 123
2 2018-11-22 12:03 SUCCESS 123我要做的是将这两条记录连接在一起,最初我在CustomerID上这样做,但这显然会造成重复,因为customerID在表2和表1中出现了两次。然后我试图缩小范围,说明DateOfInteraction < DateOfPurchase将消除第一条记录,但是我不确定如何匹配第二条记录?
结果应该是
[ColleagueID] [DateOfInteraction] [CustomerID] [PurchaseID] [DateOfPurchase] [PurchaseOutcome]
---------------------------------------------------------------------------------------------------
A 2018-11-22 12:00 123 1 2018-11-22 12:01 FAIL
B 2018-11-22 12:02 123 2 2018-11-22 12:03 SUCCESS发布于 2018-11-24 14:54:16
我认为apply做你想做的事:
select p.*, i.*
from purchases p outer apply
(select top (1) i.*
from interactions i
where i.customer_id = p.customer_id and
i.DateOfInteraction < p.DateOfPurhase
order by i.DateOfInteraction desc
) i;https://stackoverflow.com/questions/53459350
复制相似问题