Column value based on maximum of two dates

假如想象 提交于 2021-01-29 12:46:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!