Combine intersecting ranges to produce new ranges based on the points of intersection I have a table with data like this:

ID  valid_from          valid_to             item_a    Item_b    Item_c
1   20.5.2016 15:28:02  21.5.2016 7:12:49    1         2          -
1   21.5.2016 7:12:50   17.6.2016 8:49:29    1         4          -
1   17.6.2016 8:49:30   31.12.2999           1         5          -
1   24.6.2016 11:23:13  31.12.2999           -         -          6 


The last two rows have validity ranges that intersect. More specifically, one of the ranges is longer, so the period from 24.6.2016 11:23:13 to 31.12.2999 is covered by both ranges. I want that to be returned as a single row for all three items. And I want the longer range to be cut off at the beginning of the common subrange, i.e. at 24.6.2016 11:23:13.

So I would like the output to look like this:

ID  valid_from          valid_to             Item_a    Item_b    Item_c
1   20.5.2016 15:28:02  21.5.2016 7:12:49    1         2          -
1   21.5.2016 7:12:50   17.6.2016 8:49:29    1         4          -
1   17.6.2016 8:49:30   24.6.2016 11:23:13   1         5          -
1   24.6.2016 11:23:13  31.12.2999           1         5          6 


How should I write my query to solve this problem?
My guess

select ID, valid_from
  , lead(valid_from,1,'31.12.2999') over (partition by id order by valid_from) as valid_to
  , case Item_a when '-' then lag(Item_a,1,'-') over (partition by id order by valid_from) else Item_a end as Item_a
from t