简体   繁体   English

Postgresql - 组内的最小/最大日期范围

[英]Postgresql - min/max date range within group

We have a transactional table that stores the data much like a historical table where any time a status changes (or other attributes) it gets effective dated.我们有一个存储数据的事务表,就像一个历史表一样,只要状态发生变化(或其他属性),它就会生效。

Example:例子:

  Product | Status   | Start Date | End Date
----------+------- --+------------+-----------
widget a  | active   | 02/01/2020 | 02/30/2020
widget a  | active   | 03/01/2020 | 03/19/2020
widget a  | inactive | 03/20/2020 | 05/01/2020
widget a  | active   | 05/02/2020 | 08/31/2020
widget b  | active   | 02/01/2020 | 05/31/2020
widget b  | inactive | 06/01/2020 | 06/31/2020

I am trying to roll up this data based on the min and max dates as the status changes (as I said, other attributes contribute to the record changing, but I am only concerned with status changes).我正在尝试根据状态更改时的最小和最大日期汇总此数据(正如我所说,其他属性会导致记录更改,但我只关心状态更改)。 So in above example, 'widget a' would have three records: active from 02/01/2020 - 03/19/2020, inactive from 03/20/2020 - 05/01/2020 and active from 05/02/2020 - 08/31/2020.所以在上面的例子中,“widget a”将有三个记录:从 02/01/2020 - 03/19/2020 开始,从 03/20/2020 - 05/01/2020 开始不活跃,从 05/02/2020 开始活跃 - 2020 年 8 月 31 日。 This can easily be done using an ETL tool but I would like to get this into a view.这可以使用 ETL 工具轻松完成,但我想将其纳入视图。

What is the best way to do this while being mindful of performance在注意性能的同时做到这一点的最佳方法是什么

This is postgresql 10这是 PostgreSQL 10

This is a gaps-and-islands problem, where you want to group together adjacent rows that have the same product and status.这是一个间隙和孤岛问题,您希望将具有相同产品和状态的相邻行组合在一起。

Here is an approach that uses the difference between row numbers to build the groups:这是一种使用行号之间的差异来构建组的方法:

select product, status, min(start_date) start_date, max(end_date) end_date
from (
    select t.*, 
        row_number() over(partition by product order by start_date) rn1,
        row_number() over(partition by product, status order by start_date) rn2
    from mytable t
) t
group by product, rn1 - rn2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM