【发布时间】:2014-12-12 11:33:49
【问题描述】:
我刚从 Gord Thompson 那里得到了关于类似问题 (Combine two tables by joining on the same date or closest prior date (not just exact matches)) 的大力帮助,但现在意识到我的数据不是我所期望的。事实证明,我的 Lead_Dates 可以晚于 Product_Interest_Dates,这导致之前的 SQL 代码放弃了这些情况。更具体地说:
我有两张桌子:
- 客户 ID
- Lead_Date
- Lead_Source
和
- 客户 ID
- Product_Interest_Date
- Product_Interest
我想要两个创建一个表,其中对于每个 CustomerID,每个 Product_Interest 都连接到最接近日期的 Lead_Source(之前或之后)。决赛桌将是:
CustomerID
Product_Interest_Date
Product_Interest
Lead_Date (the closest entry in time to Product_Interest_Date)
Lead_Source (the Lead_Source of the closest Lead_Date)
我研究了 Gord 的代码,但无法将其带回家。按照他的例子,我想要这个:http://i.stack.imgur.com/4ZVDV.jpg
序列的 SQL 堆栈溢出新 1
SELECT
pi.CustomerID,
pi.Product_Interest_Date,
l.Lead_Date,
Abs(pi.Product_Interest_Date-l.Lead_Date) AS Date_Gap
FROM
Test_PI pi
INNER JOIN
Test_Leads l
堆栈溢出新 2
SELECT
[Stack Overflow NEW 1].CustomerID,
[Stack Overflow NEW 1].Product_Interest_Date,
Min([Stack Overflow NEW 1].Date_Gap) AS MinOfDate_Gap
FROM [Stack Overflow NEW 1]
GROUP BY [Stack Overflow NEW 1].CustomerID,
[Stack Overflow NEW 1].Product_Interest_Date;
决赛
SELECT Test_PI.CustomerID,
Test_PI.Product_Interest_Date,
Test_PI.Product_Interest,
Test_Leads.Lead_Date,
Test_Leads.Lead_Source
FROM (Test_PI INNER JOIN ([Stack Overflow NEW 2]
INNER JOIN [Stack Overflow NEW 1]
ON ([Stack Overflow NEW 2].CustomerID = [Stack Overflow NEW 1].CustomerID)
AND ([Stack Overflow NEW 2].Product_Interest_Date = [Stack Overflow NEW 1].Product_Interest_Date)
AND ([Stack Overflow NEW 2].MinOfDate_Gap = [Stack Overflow NEW 1].Date_Gap))
ON (Test_PI.CustomerID = [Stack Overflow NEW 2].CustomerID)
AND (Test_PI.Product_Interest_Date = [Stack Overflow NEW 2].Product_Interest_Date))
INNER JOIN Test_Leads
ON ([Stack Overflow NEW 1].CustomerID = Test_Leads.CustomerID)
AND ([Stack Overflow NEW 1].Lead_Date = Test_Leads.Lead_Date)
GROUP BY Test_PI.CustomerID, Test_PI.Product_Interest_Date, Test_PI.Product_Interest, Test_Leads.Lead_Date, Test_Leads.Lead_Source;
我试图将所有这些组合成一个代码,但无法通过 SQL FROM 错误!这是我的具体问题,如何在单个 SQL 代码中编写?
SELECT
Test_PI.CustomerID,
Test_PI.Product_Interest_Date,
Test_PI.Product_Interest,
Test_Leads.Lead_Date,
Test_Leads.Lead_Source
FROM
(Test_PI
INNER JOIN
( (SELECT
latest.CustomerID,
latest.Product_Interest_Date,
Min(latest.Date_Gap) AS Min_Date_Gap
FROM
latest
) latest1
INNER JOIN
(SELECT
pi.CustomerID,
pi.Product_Interest_Date,
l.Lead_Date,
Abs(pi.Product_Interest_Date - l.Lead_Date) AS Date_Gap
FROM
Test_PI pi
INNER JOIN
Test_Leads l
ON pi.CustomerID = l.CustomerID
) latest
)
ON Test_PI.CustomerID = latest1.CustomerID AND Test_PI.Product_Interest_Date = latest1.Product_Interest_Date
INNER JOIN
Test_Leads
ON Test_Leads.CustomerID = latest1.CustomerID
AND Test_Leads.Lead_Date = latest1.Lead_Date
【问题讨论】: