GROUP BY consecutive dates delimited by gaps

后端 未结 2 1902
忘了有多久
忘了有多久 2021-01-04 10:42

Assume you have (in Postgres 9.1 ) a table like this:

date | value 

which have some gaps in it (I mean: not every possible date between min

2条回答
  •  孤街浪徒
    2021-01-04 11:33

    Here is a way of solving it.

    First, to get the beginning of consecutive series, this query would give you the first date:

    SELECT first.date
    FROM raw_data first
         LEFT OUTER JOIN raw_data prior_first ON first.date = prior_first + 1
    WHERE prior_first IS NULL
    

    likewise for the end of consecutive series,

    SELECT last.date
    FROM raw_data last
         LEFT OUTER JOIN raw_data after_last ON last.date = after_last - 1
    WHERE after_last IS NULL
    

    You might consider making these views, to simplify queries using them.

    We only need the first to form group ranges

    CREATE VIEW beginings AS
    SELECT first.date
    FROM raw_data first
         LEFT OUTER JOIN raw_data prior_first ON first.date = prior_first + 1
    WHERE prior_first IS NULL
    
    CREATE VIEW endings AS
    SELECT last.date
    FROM raw_data last
         LEFT OUTER JOIN raw_data after_last ON last.date = after_last - 1
    WHERE after_last IS NULL
    
    SELECT MIN(raw.date), MAX(raw.date), SUM(raw.value)
    FROM raw_data raw
      INNER JOIN (SELECT lo.date AS lo_date, MIN(hi.date) as hi_date
                  FROM beginnings lo, endings hi
                  WHERE lo.date < hi.date
                  GROUP BY lo.date) range
         ON raw.date >= range.lo_date AND raw.date <= range.hi_date
    GROUP BY range.lo_date
    

提交回复
热议问题