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

时间:2019-05-08 21:28:19

标签: sql postgresql window

我有以下数据表

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'的新列中创建和分配值。我想在当天和前一天的delta = 0daily_cumulative_precip > 0delta = 1的时候分别有daily_cumulative_precip = 0delta = 2daily_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;

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

对于您的特定数据,可以使用以下功能:

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 <>小提琴。

答案 1 :(得分:2)

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

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;