根据连续出现确定最小日期

Determine MIN Date from Consecutive Occurrences

我有一个 table,其中包含以下列:日期、客户、活动标志。我需要添加名为 Start 的第四列。根据连续的活动标志,“开始”列应该 return 客户端处于活动状态的第一个日期。

显示我目前拥有的三列以及我希望 return 开始列的结果。

如果您能深入了解我的 SQL 代码实现此目标的方式,我们将不胜感激。谢谢!!

如果我假设每个客户每月一个日期,您可以在没有子查询的情况下执行此操作:

select t.*,
       (case when activeflag = 1
             then coalesce(max(case when activeflag = 0 then date end) over (partition by customer order by date) + interval '1 month',
                           min(case when activeflag = 1 then date end) over (partition by customer)
                          )
        end) as start
from t;

不过,子查询可能会使这更容易。您可以将其视为间隙和孤岛问题:

select t.*,
       (case when activeflag = 1
             then min(date) over (partition by customerid, seqnum - seqnum_a)
        end) as start
from (select t.*,
             row_number() over (partition by customerid order by date) as seqnum,
             row_number() over (partition by customerid, activeflag order by date) as seqnum_a
      from t
     ) t