Aggregate continuous ranges of dates Aggregate continuous ranges of dates postgresql postgresql

Aggregate continuous ranges of dates


SELECT min(reserved_date) AS start_date     , max(reserved_date) AS end_dateFROM  (   SELECT reserved_date        , reserved_date - row_number() OVER (ORDER BY reserved_date)::int AS grp   FROM   reserved_dates   ) sub GROUP  BY grpORDER  BY grp;
  1. Compute a running, gap-less number in chronological order with the window function row_number() - unless your reserved_days_id happens to be gap-less and in chronological order, which is typically not the case.

  2. Deduct that from reserved_date in each row (after converting to integer). Consecutive days end up with the same date value grp - which has no other purpose or meaning than to form groups.

  3. Aggregate in the outer query. Voilá.

SQL Fiddle.

Similar cases: