【问题标题】:Select minimum value by value transition in PostgreSQL在 PostgreSQL 中按值转换选择最小值
【发布时间】:2019-09-24 18:08:17
【问题描述】:

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

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

任何帮助将不胜感激:)

【问题讨论】:

    标签: sql postgresql gaps-and-islands


    【解决方案1】:

    这是一个典型的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

    【讨论】:

      【解决方案2】:

      我想我想出了一个答案:

      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
      

      【讨论】:

      猜你喜欢
      • 2015-08-27
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      相关资源
      最近更新 更多