【发布时间】:2021-12-28 08:12:32
【问题描述】:
谁能帮我解决这个问题?
我有两个表,表 A 具有 product-id 和 Order-no 作为键,表 B 具有 Product-Id、Order-no(作为键)以及 Update_Timestamp、订单状态等。 ;试图获取表 A 中存在的所有匹配的 Product-Id 和 Order-number 已 a) 表 B 中的匹配记录 - 表 B 中订单的最新时间戳 b) 表 B 中的不匹配记录 在结果集中同时获得 a) 和 b),如下所示。
产品(表 A)
| Product_id | Order_no |
|---|---|
| 1234567 | S12345 |
| 1234568 | S12346 |
| 1234569 | P12347 |
| 1234575 | M12347 |
订单详情(表 B)
| Product_id | Order_no | Update_ts | Order_stat |
|---|---|---|---|
| 1234567 | S12345 | 2020-05-05-05.01.02.123455 | P |
| 1234567 | S12345 | 2020-06-05-05.01.02.123455 | P |
| 1234567 | S12345 | 2020-07-05-05.01.02.123455 | C |
| 1234568 | S12346 | 2021-05-05-06.01.02.123456 | C |
| 1234569 | P12347 | 2021-05-05-06.01.02.000145 | C |
| 1234569 | P12347 | 2021-06-05-06.01.02.000145 | C |
| 1234569 | P12347 | 2021-07-05-06.01.02.000145 | M |
| 1234569 | P12347 | 2021-08-05-06.01.02.000145 | P |
| 1234574 | T12347 | 2021-07-05-06.01.02.000145 | P |
预期结果
| Product_id | Order_no | Update_ts | Order_stat |
|---|---|---|---|
| 1234569 | P12347 | 2021-08-05-06.01.02.000145 | P |
| 1234575 | M12347 | NULL | NULL |
查询:如果 Order_stat 需要过滤,例如产品 ID 的“P”订单状态,如果该订单状态存在且所有匹配订单的最新时间戳以及不匹配的记录为更多? .
编辑:尝试了以下查询,但出现错误:AN ON CLAUSE IS INVALID. SQLCODE=-338, SQLSTATE=42972, DRIVER=4.24.92。此错误已通过建议的最新查询解决,并希望对上述查询提出任何建议
您对如何获得预期结果有什么建议吗?
select
aa.Product_id
,aa.Order_no
,bb.Update_ts
,bb.Order_stat
from
Product aa
Left join
Orderdetails bb
on aa.product_id =bb.product_id
and aa.order_no =bb.order_no
and bb.update_ts =(select max(cc.update_ts) from Orderdetails cc
where cc.product_id = bb.product_id
and cc.order_no = bb.order_no
and cc.order_stat = bb.order_stat)
【问题讨论】: