假设我有一个表,其中有一个每天生成的日期列,如下所示。
table 1
ID name qty date
1 abc 20 17/01/2022
1 abc 10 18/01/2022
2 def 10 24/01/2022
2 def 40 25/01/2022
2 def 67 26/01/2022
table 2
ID name price_dt price
1 abc 18/01/2022 23.56
1 abc 17/01/2022 10.56
1 abc 16/01/2022 44.33
1 abc 15/01/2022 56.11
2 def 25/01/2022 2.98
2 def 26/01/2022 4.92
2 def 27/01/2022 4.88
2 def 24/01/2022 3.33
2 def 23/01/2022 8.47
2 def 22/01/2022 3.89
我将 table1 与 table2 连接起来,我只需要小于日期列的最近的 Price_dt 记录。这可以通过连接 2 个表并通过对 Price_dt DESC 进行排序来删除重复项来完成,但挑战是表大小如此之大,并且连接不可行。所以我希望在加入之前减少表 2 中的行数。
我在 python 中尝试的代码并在 sql 中寻找类似的东西
DF_A['date'] = pd.to_datetime(DF_A['date'], dayfirst=True)
DF_B['price_dt'] = pd.to_datetime(DF_B['price_dt'], dayfirst=True)
out = pd.merge_asof(DF_A.sort_values('date'),
DF_B.sort_values('price_dt'),
left_on='date',
right_on='price_dt',
by=['ID','name'],
allow_exact_matches=False)
预期_DF:
ID name qty date price_dt price
1 abc 20 17/01/2022 16/01/2022 44.33
1 abc 10 18/01/2022 17/01/2022 10.56
2 def 10 24/01/2022 23/01/2022 8.47
2 def 40 25/01/2022 24/01/2022 3.33
2 def 67 26/01/2022 25/01/2022 2.98
如何使用SQL获取上述结果
--Return the most recent price_dt for each ID less than table1.date
SELECT t1.ID, t1.name, Max(t2.price_dt) as MaxPrice_dt
FROM table1 t1
INNER JOIN table2 t2 on t1.ID=T2.ID AND t1.date > t2.price_dt
GROUP BY t1.ID, t1.name
身份证 | 名字 | 最大价格_dt |
---|---|---|
1 | abc | 2022-01-17 |
2 | 定义 | 2022-01-25 |