PostgreSQL:在事件中分割时间段 [英] postgresql: splitting time period at event

查看:139
本文介绍了PostgreSQL:在事件中分割时间段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张国家时期表。在某些情况下,某些国家/地区属性(例如首都)会在一段时间内的某个日期发生变化。在这里,我想将国家/地区时段分为两个新时期,一个是此变更之前,另一个是变更之后。

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.

示例:

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

所需的输出:

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

我考虑从 generate_series 开始,遵循以下原则:

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?

推荐答案

您可以执行 UNION 代替。这样,您就不会生成不必要的行

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

这是一个 SQLFiddle 演示

输出:


| 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) |

这篇关于PostgreSQL:在事件中分割时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆