我刚从Gord Thompson得到了一个类似问题的大力帮助(通过加入相同日期或最接近的日期(不仅仅是完全匹配)来合并两个表)但现在意识到我的数据不是我所期望的.事实证明,我可以在Product_Interest_Dates之后使用Lead_Dates,这导致以前的SQL代码丢弃这些情况.进一步来说:
我有两张桌子:
和
我想要两个创建一个表,其中,对于每个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)
Run Code Online (Sandbox Code Playgroud)
我研究了戈德的代码,但不能带回家.按照他的例子,图形上我想要这个: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
Run Code Online (Sandbox Code Playgroud)
Stack Overflow NEW 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] …
Run Code Online (Sandbox Code Playgroud) 这是我的代码的简化版本.我正在尝试使用以下方法写入文件:
fileName = "missing.csv"
for x in range (0,5):
print(x)
saveData = open(fileName, "a")
saveData.write(str(x)+'\n')
saveData.close
Run Code Online (Sandbox Code Playgroud)
控制台打印:
0, 1, 2, 3, 4
Run Code Online (Sandbox Code Playgroud)
... 正如它应该.但是,当我打开missing.csv时,它只包含:
0
1
2
3
Run Code Online (Sandbox Code Playgroud)
没有最后一个条目(4).
有任何想法吗?请指教.
我有两张表:
和
我希望两个创建一个表,其中对于每个 CustomerID,每个 Product_Interest 连接到最接近日期(但不是之后)的 Lead_Source。决赛桌将是:
到目前为止,我可以连接表,并创建一个新字段来计算最接近的日期而无需遍历,但是当我尝试使用 Min 进行分组时,我仍然得到多个排列(每个 Lead_Date 到每个 Product_Interest)。这是代码:
SELECT Min(Int(Abs([Test_PI]![Product_Interest_Date]-[Test_Leads]![Lead_Date])))
AS Lead_PI_Link,
Test_Leads.CustomerID,
Test_PI.Product_Interest_Date,
Test_PI.Product_Interest,
Test_Leads.Lead_Date,
Test_Leads.Lead_Source
FROM Test_Leads INNER JOIN Test_PI ON Test_Leads.CustomerID = Test_PI.CustomerID
GROUP BY Test_Leads.CustomerID,
Test_PI.Product_Interest_Date,
Test_PI.Product_Interest,
Test_Leads.Lead_Date,
Test_Leads.Lead_Source
HAVING (((Test_Leads.CustomerID)="C6UJ9A002Q2P"));
Run Code Online (Sandbox Code Playgroud)
此 CustomerID 在 Test_Leads 中有 4 个条目,在 Product_Interest 中有 4 个条目。此查询的结果给出 16 个结果,而不是所需的 4 个结果。如果日期完全匹配,我可以添加一个条件,即日期差异为“0”,但是,有时这些日期会偏移 1 天,有时会偏移 1 天。很多天。
我正在使用 Access,并且更喜欢“本机”解决方案,但此时我已经做好了一切准备!