我有一个按“日期”列排序的表格
日期 | 价值 |
---|---|
2023 年 1 月 1 日 | 10 |
2023 年 1 月 2 日 | |
2023 年 1 月 3 日 | |
2023 年 1 月 4 日 | 20 |
2023 年 1 月 5 日 | |
2023 年 1 月 6 日 | 40 |
2023 年 1 月 7 日 | 42 |
2023 年 1 月 8 日 | 3 |
2023 年 1 月 9 日 | |
2023 年 1 月 10 日 | 1 |
我想创建这样的结果。其中“counts”列是“value”列中紧邻当前行上方的行数。
日期 | 价值 | 计数 |
---|---|---|
2023 年 1 月 1 日 | 10 | 0 |
2023 年 1 月 4 日 | 20 | 2 |
2023 年 1 月 6 日 | 40 | 1 |
2023 年 1 月 7 日 | 42 | 0 |
2023 年 1 月 8 日 | 3 | 0 |
2023 年 1 月 10 日 | 1 | 1 |
这可以通过 redshift 中的查询来完成吗?
您标记了窗口函数的问题,因此您看到这很可能得到解决。
这是一个解决方案(我将日期更改为 dt,将值更改为 val,因为使用关键字作为列名通常不是您想要的位置):
with prec_null as (
select *,
count(case when val is null then 1 else null end)
over (order by dt rows unbounded preceding) as cnt
from test )
select dt, val, cnt - coalesce(lag(cnt) over(order by dt), 0) as cnt
from prec_null
where val is not null
order by dt;