Skip to content
Advertisement

Is there a way to group values getting only the ones that verifies certain condition?

I’m trying to write a query in Oracle SQL that aggregates values by some ids, where I have the following table as an input:

ID SOME_DATE RANK_POSITION
301 20211201 1
301 20211202 2
301 20211203 3
649 20211201 1
649 20211202 2
649 20211206 3
649 20211208 4
649 20211211 5
758 20211212 1
758 20211222 2

And y want to obtain something like this:

ID FIRST_IN_RANK_DATE SECOND_IN_RANK_DATE
301 01/12/2021 02/12/2021
649 01/12/2021 02/12/2021
758 12/12/2021 22/12/2021

Where FIRST_IN_RANK_DATE, is the date that is the first in the RANK_POSITION for the ID, and SECOND_IN_RANK_DATE is the date that is second in RANK_POSITION for the specific ID.

Advertisement

Answer

You can use conditional aggregation:

Or PIVOT:

Or, from Oracle 12, MATCH_RECOGNIZE:

Which, for the sample data:

All output:

ID FIRST_IN_RANK_DATE SECOND_IN_RANK_DATE
301 2021-12-01 00:00:00 2021-12-02 00:00:00
649 2021-12-01 00:00:00 2021-12-02 00:00:00
758 2021-12-12 00:00:00 2021-12-22 00:00:00

db<>fiddle here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement