问题
I am trying to get the value of a column based on the maximum of two dates.
I have tried this, to get the maximum of two dates.
SELECT VIN,
MAX(CASE WHEN DELIVERY_TYPE = 25 THEN TRANSACTION_DATE END) AS DELIVERY_DATE,
MAX(CASE WHEN DELIVERY_TYPE <> 25 THEN TRANSACTION_DATE END) AS TRANSACTION_DATE
FROM TABLE
WHERE VIN IN ('XYZ')
GROUP BY VIN;
I get this, which is what I need.But I need the delivery code.
VIN DELIVERY_DATE OTHER_DELIVERY DATE
XYZ 26-DEC-18 01-MAY-19
How do I get this
VIN DELIVERY_DATE OTHER_DELIVERY DATE Delivery_code
XYZ 26-DEC-18 01-MAY-19 010
Source data is this:
VIN TRANSACTION_DATE Delivery_code
XYZ 26-DEC-18 025
XYZ 01-MAY-19 010
EDIT: New data source
VIN TRANSACTION_DATE DELIVERY_TYPE
xzy 10-APR-19 025
xyz NULL 010
xzy 12-JUL-19 035
回答1:
You can use keep
:
SELECT VIN,
MAX(CASE WHEN DELIVERY_TYPE = 25 THEN TRANSACTION_DATE END) AS DELIVERY_DATE,
MAX(CASE WHEN DELIVERY_TYPE <> 25 THEN TRANSACTION_DATE END) AS TRANSACTION_DATE,
MAX(DELIVERY_CODE) KEEP (DENSE_RANK FIRST ORDER BY TRANSACTION_DATE DESC NULLS LAST) as DELIVERY_CODE
FROM TABLE
WHERE VIN IN ('XYZ')
GROUP BY VIN;
来源:https://stackoverflow.com/questions/57084651/column-value-based-on-maximum-of-two-dates