postgresql: splitting time period at event

谁说胖子不能爱 提交于 2020-01-05 05:30:24

问题


I have a table of country-periods. In some cases, certain country attributes (e.g. the capital) changes on a date within a time period. Here I would like to split the country-period into two new periods, one before and one after this change.

Example:

Country |  start_date   |  end_date   | event_date 
   A    |  1960-01-01   | 1999-12-31  | 1994-07-20
   B    |  1926-01-01   | 1995-12-31  | NULL

Desired output:

Country |  start_date   |  end_date   | event_date 
   A    |  1960-01-01   | 1994-07-19  | 1994-07-20
   A    |  1994-07-20   | 1999-12-31  | 1994-07-20
   B    |  1926-01-01   | 1995-12-31  | NULL

I considered starting off with generate_series along these lines:

SELECT country, min(p1) as sdate1, max(p1) as sdate2,
min(p2) as sdate2, min(p2) as edate2 
  FROM 
   (SELECT country, 
    generate_series(start_date, (event_date-interval '1 day'), interval '1 day')::date as p1,
    generate_series(event_date, end_date, interval '1 day')::date as p2
   FROM table)t 
GROUP BY country

But these seems way to inefficient and messy. Unfortunately I don't have any experience when it comes to writing functions. Any ideas on how I can solve this?


回答1:


You can do UNION instead. This way you don't generate unnecessary rows

SELECT country, start_date, 
       CASE WHEN event_date BETWEEN start_date AND end_date 
            THEN event_date - 1 
            ELSE end_date
       END AS end_date, event_date
  FROM table1
 UNION ALL
SELECT country, event_date, end_date, event_date
  FROM table1
 WHERE event_date BETWEEN start_date AND end_date
 ORDER BY country, start_date, end_date, event_date

Here is a SQLFiddle demo

Output:

| country | start_date |   end_date | event_date |
|---------|------------|------------|------------|
|       A | 1960-01-01 | 1994-07-19 | 1994-07-20 |
|       A | 1994-07-20 | 1999-12-31 | 1994-07-20 |
|       B | 1926-01-01 | 1995-12-31 |     (null) |


来源:https://stackoverflow.com/questions/45354530/postgresql-splitting-time-period-at-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!