MS Access中根据ProductMade时间匹配ProductID与ShippingID的技术问询
如何在MS Access中根据时间区间匹配ProductID与ShippingID?
需求说明:
需要为每个ProductID匹配对应的ShippingID,规则是判断Product表的ProductMade时间落在Shipping表的ShippingTime区间内(即找到小于等于ProductMade的最大ShippingTime,对应其ShippingID)。使用MS Access作为数据源,尝试多种SQL语句未得到预期结果,不清楚如何正确实现该逻辑。
数据表结构与数据
Product表
| ProductID | ProductMade |
|---|---|
| 11205 | 2024-05-29 17:27 |
| 11921 | 2024-05-29 17:12 |
| 12324 | 2024-05-29 16:53 |
| 12328 | 2024-05-29 16:37 |
| 11851 | 2024-05-29 15:54 |
| 12354 | 2024-05-29 14:13 |
| 12333 | 2024-05-29 13:51 |
| 12342 | 2024-05-29 13:36 |
| 20014 | 2024-05-29 13:16 |
| 11822 | 2024-05-29 12:52 |
Shipping表
| ShippingTime | ShippingID |
|---|---|
| 2024-05-29 12:49 | I0230 |
| 2024-05-28 19:31 | J0130 |
| 2024-05-29 05:04 | J0140 |
| 2024-05-29 13:37 | J0340 |
| 2024-05-29 17:05 | J0410 |
| 2024-05-28 17:07 | J0430 |
| 2024-05-29 11:24 | K0120 |
| 2024-05-29 07:01 | K0310 |
| 2024-05-28 15:01 | K0510 |
| 2024-05-28 23:43 | K0830 |
| 2024-05-29 01:48 | K0940 |
| 2024-05-29 10:12 | K1020 |
| 2024-05-29 15:57 | K1030 |
| 2024-05-28 22:02 | K1220 |
| 2024-05-29 03:41 | K1240 |
| 2024-05-29 15:51 | K1340 |
解决方案
方法1:使用子查询实现匹配
该方法通过子查询为每个ProductMade时间筛选出小于等于它的最新ShippingTime,并返回对应的ShippingID:
SELECT p.ProductID, p.ProductMade, (SELECT TOP 1 s.ShippingID FROM Shipping s WHERE s.ShippingTime <= p.ProductMade ORDER BY s.ShippingTime DESC) AS ShippingID FROM Product p;
方法2:使用Access特有的DMax函数
利用DMax函数直接获取符合条件的最大ShippingTime,再关联Shipping表获取对应ID:
SELECT p.ProductID, p.ProductMade, s.ShippingID FROM Product p INNER JOIN Shipping s ON s.ShippingTime = DMax("ShippingTime", "Shipping", "ShippingTime <= #" & Format(p.ProductMade, "yyyy-mm-dd hh:nn:ss") & "#");
结果验证
以部分数据为例:
- ProductID 11205(2024-05-29 17:27)→ 匹配ShippingID J0410(对应ShippingTime 2024-05-29 17:05)
- ProductID 11851(2024-05-29 15:54)→ 匹配ShippingID K1340(对应ShippingTime 2024-05-29 15:51)
- ProductID 12342(2024-05-29 13:36)→ 匹配ShippingID I0230(对应ShippingTime 2024-05-29 12:49)
内容的提问来源于stack exchange,提问作者Joakim Åhl
相关产品推荐
相关产品推荐

