[英]Oracle SQL - Selecting first inspection row after delivery row
我正在努力解决以下问题。
tblTrans
中的数据如下:
| Transaction_ID | Transaction_Type | Hours | Employee_ID |
|:--------------:|:---------------------:|:-----:|:-----------:|
| 107 | In-Place Delivery | 0.60 | SDK |
| 110 | In-Place Delivery | 0.88 | SDK |
| 112 | Inspection | 1.22 | SDK |
| 114 | In-Place Delivery | 2.11 | JMK |
| 115 | Inspection | 0.01 | SDK |
| 116 | Inspection | 0.64 | JMK |
| 239 | Out-of-Place Delivery | 0.12 | JMK |
| 241 | In-Place Delivery | 0.33 | JMK |
| 255 | Out-of-Place Delivery | 0.87 | KWE |
| 256 | Inspection | 5.90 | JMK |
| 263 | Inspection | 11.80 | SDK |
| 291 | In-Place-Delivery | 1.00 | SDK |
| 292 | Inspection | 0.04 | JMK |
| 400 | Out-of-Place Delivery | 9.50 | JMK |
| 401 | Inspection | 1.21 | JMK |
我想要完成的是确定每个 In-Place Delivery之后的第一个检查事务,创建一个如下所示的表:
| Delivery_Transaction_ID | First_Inspection |
|:-----------------------:|:----------------:|
| 107 | 112 |
| 110 | 112 |
| 114 | 115 |
| 241 | 256 |
| 291 | 292 |
交付后即将进行的检查的Transaction_ID
将始终大于先前的交付。 它按顺序进行。 但是,它可能不一定是 +1,因为有时系统会跳转数字。 但是,它总是会更大。
到目前为止,我已经尝试了以下查询的一些变体:
WITH
In_Place_Deliveries AS (
SELECT
Transaction_ID AS Delivery_Transaction
FROM
tblTrans
WHERE
Transaction_Type = 'In-Place Delivery'
),
SELECT
ipd.Delivery_Transaction,
LEAD(MIN(Transaction_ID)) OVER (ORDER BY Transaction_Type) AS "First_Inspection"
FROM
tblTrans
INNER JOIN In_Place_Deliveries ipd on ipd.Delivery_Transaction = tblTrans.Transaction_ID
但我得到:
| DELIVERY_TRANSACTION | First_Inspection |
|:--------------------:|:----------------:|
| 107 | 110 |
| 110 | 114 |
| 114 | 241 |
| 241 | (null) |
这显然是不正确的。
我在这里设置了一个SQL FIDDLE ,用于演示目的,带有数据和查询。
如何重新设计查询以实现所需的 output?
只需使用 LEAD IGNORE NULLS:
WITH In_Place_Deliveries AS
(
SELECT
Transaction_ID AS Delivery_Transaction ,
Transaction_Type,
-- next Inspection
lead(case when Transaction_Type = 'Inspection' then Transaction_ID end ignore nulls)
OVER (ORDER BY Transaction_ID)
FROM
tblTrans
WHERE
Transaction_Type IN ( 'In-Place Delivery', 'Inspection')
)
SELECT *
FROM In_Place_Deliveries
WHERE Transaction_Type = 'In-Place Delivery'
见小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.