Skip to content
Advertisement

Find date difference in Oracle SQL based on condition

I have a table:

table1

DEMO – Link

Here is the logic:

I need to find the day difference between two trans_id for a member sorted by start_date where there is no overlapping start_date and end_date.

We need to check the max end_date for a user processing one record at a time.

The logic would be:

For a member:

  • sort all records by user_id and start_date
  • trans_id = 1, end_date = 18-06-2018 , set max_end_date = 18-06-2018
  • trans_id = 2, end_date = 14-06-2018, end_date < max_end_date, move forward
  • trans_id = 3, end_date = 19-07-2018, end_date > max_end_date, add a record in output where
    • transidfrom = 1 (as this is the record with max_end_date)
    • transidto = 4 (as this is the record where end_date > max_end_date)
    • transidfrom_end_date = 18-06-2018, pick the end_date of trans_id of transidfrom
    • transidto_start_date = 19-07-2018, pick the start_date of trans_id of transidto
    • datediff = transidto_start_datetransidfrom_end_date

The output would be as follows:

table2

Is there a way to do this in Oracle SQL in 1 query?

Advertisement

Answer

If I have understood your requirement correctly, then maybe this will do it:

SQL Fiddle example

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