Select PostgreSQL 中按值转换的最小值

Select minimum value by value transition in PostgreSQL

我有一个 table,其中包含一些与商店中的文章相关的数据:

Article     Date         Stored
A           22/08/2019   True
A           23/08/2019   True
A           24/08/2019   True
A           25/08/2019   False
A           26/08/2019   True
A           27/08/2019   True
A           28/08/2019   False
A           29/08/2019   False
A           30/08/2019   True

我想得到的是 A 的值 Stored=True 和值 Stored=False 的最小日期:

Article     Date         Stored
A           22/08/2019   True
A           25/08/2019   False

但是,我们假设,对于文章 A,在 Stored=False 之后有数据 Stored=True(日期 26/08/2019)。在这种情况下,我也想显示这个最小值。综上所述,我想要的是每次发生转换时的最小日期值(即,Stored 从 True 到 False 或从 False 到 True):

所以我的最终结果是这样的:

Article     Date         Stored
A           22/08/2019   True
A           25/08/2019   False
A           26/08/2019   True
A           28/08/2019   False
A           30/08/2019   True

任何帮助将不胜感激:)

我想我想出了一个答案:

select article,date,stored from(
select
article,date,stored,lag(stored) over (order by date) stored_previous_value from my_table
)q1
where stored!=stored_previous_value or stored_previous_value is null

这是一个典型的 gaps-and-islands 问题。可以使用row_number()解析函数:

select article, min(date) as date, stored
  from (
        select *,
               row_number() over (partition by article, stored order by date) as rn1,
               row_number() over (partition by article order by date) as rn2
          from tab 
       ) t
 group by article, stored, rn1 - rn2
 order by date;

Demo