Search code examples
sqloracle-databasesubquery

Count only original seconds with Oracle SQL


I have a table with this structure and data, with start and stop positions of an audio/video. I have to count the original seconds and discard the not original ones.

E.g.

    CUSTOMER_ID ITEM_ID CHAPTER_ID  START_POSITION  END_POSITION
A   123456      1       6           0               97
B   123456      1       6           97              498
C   123456      1       6           498             678
D   123456      1       6           678             1332
E   123456      1       6           1180            1190
F   123456      1       6           1190            1206
G   123456      1       6           1364            1529
H   123456      1       6           1530            1531

Original Data

Lines "E" and "F" does not represent original seconds because "D" line starts at 678 and finishes with 1332 so I need to create a new set of lines like this:

    CUSTOMER_ID ITEM_ID CHAPTER_ID  START_POSITION  END_POSITION
A   123456      1       6           0               97
B   123456      1       6           97              498
C   123456      1       6           498             678
D   123456      1       6           678             1332
E   123456      1       6           1364            1529
F   123456      1       6           1530            1531

New Result Set

Can you help mw with this?


Solution

  • If I am following you correctly, you can use not exists to filter out rows whose range is contained in the range of another row:

    select t.*
    from mytable t
    where not exists (
        select 1
        from mytable t1
        where 
            t1.customer_id = t.customer_id
            and t1.start_position < t.start_position 
            and t1.end_position   > t.end_position
    )