Skip to content
Advertisement

How to do a query on Oracle SQL to get time intervals, grouping by specific fields

I love a good challenge, but this one has been breaking my head for too long. šŸ™‚

Iā€™m trying to build a query to get dates intervals, grouping the information by one field.

Let me try to explain it in a simple way. We have this table:

Table

I need to get the intervals a soldier spent on each ranking, so the end result I need to get should be something like this:

ExpectedResults

As you can see the soldier can be promoted/demoted along the time.

Any suggestion on how to build a query to do this?

THANK YOU!

Advertisement

Answer

From Oracle 12, you can use MATCH_RECOGNIZE:

Which, for the sample data:

Outputs:

  ID | NAME  | RANKING    | START_DATE          | END_DATE           
---: | :---- | :--------- | :------------------ | :------------------
1001 | Jones | Lieutenant | 2000-03-20 00:00:00 | 2004-10-01 00:00:00
1001 | Jones | Captain    | 2004-10-02 00:00:00 | 2007-02-20 00:00:00
1001 | Jones | Major      | 2007-02-21 00:00:00 | 2010-01-26 00:00:00
1001 | Jones | Captain    | 2010-01-27 00:00:00 | 2014-05-11 00:00:00
1001 | Jones | Major      | 2014-05-12 00:00:00 | 2016-04-22 00:00:00
1001 | Jones | General    | 2016-04-23 00:00:00 | 2020-11-30 00:00:00

db<>fiddle here

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