根据 Postgres 中另一列的条件生成一系列整数

Generate series of integer based on the condition of another column in Postgres

我有以下数据表

create table test.my_table
(
  date                    date,
  daily_cumulative_precip real
);


INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-11', 0.508);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-12', 0);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-13', 0);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-14', 2.032);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-15', 0);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-16', 0);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-17', 21.842);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-18', 0);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-19', 0);
INSERT INTO test.my_table (date, daily_cumulative_precip) VALUES ('2016-07-20', 0);

我想在基于 daily_cumulative_precip 的名为 'delta' 的新列中创建和分配值。我希望当天和前一天 daily_cumulative_precip > 0delta = 0daily_cumulative_precip = 0delta = 1 和前一天 delta = 2 当天 daily_cumulative_precip = 0 时和前 1 天,delta = 3daily_cumulative_precip = 0 那天和前 2 天。对于这个特定的数据表,delta 应该是

0, 1, 2, 0, 1, 2, 0, 1, 2, 3

我有以下内容,但没有产生预期的结果

SELECT *,
      CASE
        WHEN daily_cumulative_precip > 0 THEN 0
        --ELSE date - first_value(date) OVER (ORDER BY date)
          ELSE date - lag(date) OVER (ORDER BY date)
          END AS delta
FROM "test".my_table
ORDER BY date;

非常感谢您的帮助。

对于您的特定数据,以下工作:

select t.*,
       (date - max(date) filter (where daily_cumulative_precip > 0) over (order by date))
from my_table t
order by date;

这会获取值大于 0 的最近日期。

这假设第一天的值大于 0。如果情况并非总是如此,则:

select t.*,
       (date -
        coalesce(max(date) filter (where daily_cumulative_precip > 0) over (order by date),
                 min(date) over (order by date)
                )
       ) as seqnum
from my_table t
order by date;

Here 是一个 db<>fiddle.

这是一种可能的解决方案。这个想法是首先生成一个值,将您的记录分成不同的组,然后您可以计算每个组的增量。

with partitions as (
select date
     , daily_cumulative_precip
     , sum(case when daily_cumulative_precip <> 0 then 1 else 0 end)
       over (order by date) grp
  from my_table
)
select date
     , daily_cumulative_precip
     , row_number() over (partition by grp order by date) - 1 delta
  from partitions;