Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Choose latest record with conditional scenerio

bhaskar_subbiahApr 23 2019 — edited Sep 18 2019

Hi All,

Below is the scenario i am facing. I tried to explain it with sample data.

   

IDBilling_typeCREATED_DATE
1128New order01-Jan-98
1128In Billing01-Jan-01
2115In billing25-Feb-10
2115In billing27-Mar-15
2141New order01-Mar-18
2141Cancelled04-Feb-19
1786New order01-Jan-98
1786In Billing01-Jan-01
7654New order01-Mar-18
7654Cancelled04-Feb-19
7654Cancelled

09-Mar-19

The scenerio is, a single ID appears multiple time but i have to choose latest record based on max(created_date) column. But if a ID has billing_type as 'Cancelled' then we have to pick previous line item for that ID value. For ex, here for ID 2141 the latest one has billing type as cancelled, so in this case i need to select the previous one with billing type as 'New order' .

Suppose if the previous one is also 'Cancelled' ( for ID 7654) then i have to select the one before that with billing type other than 'Cancelled' .

Below is how the output should appear.

   

IDBilling_typeCREATED_DATE
1128In Billing01-Jan-01
2115In billing27-Mar-15
2141New order01-Mar-18
1786In Billing01-Jan-01
7654New order

01-Mar-18

I googled for the logic but i did not get a proper one. I think it should be something like case - When statement but i am unable to frame a right logic.

So please help me with this.

Let me know for any queries.

Thanks

Bhaskar.S

This post has been answered by mathguy on Apr 24 2019
Jump to Answer
Comments
Post Details
Added on Apr 23 2019
34 comments
1,382 views