Merge overlapping time intervals, how?

前端 未结 1 459
广开言路
广开言路 2020-12-17 07:29

Anyone could help me in a query that **merge a interval of datas?
ex: Common select:

SELECT id, date_start, date_end FROM evento ORDER BY date_s

相关标签:
1条回答
  • 2020-12-17 08:15

    You may also try this query (once more solutions beside those given by PM 77-1 in the comment above) :

    WITH RECURSIVE cte( id, date_start, date_end ) AS
    (
      SELECT id, date_start, date_end
      FROM evento
      UNION 
      SELECT e.id,
             least( c.date_start, e.date_start ),
             greatest( c.date_end, e.date_end )
      FROM cte c
      JOIN evento e
      ON e.date_start between c.date_start and c.date_end
         OR 
         e.date_end between c.date_start and c.date_end
    )
    SELECT distinct date_start, date_end
    FROM (
      SELECT id, 
             min( date_start) date_start, 
             max( date_end ) date_end
      FROM cte
      GROUP BY id
    ) xx
    ORDER BY date_start;
    

    Demo ---> http://www.sqlfiddle.com/#!12/bdf7e/9

    however for huge table the performance of this query could be horribly slow, and some procedural approach might perform better.

    0 讨论(0)
提交回复
热议问题