我正在尝试用类似的东西创建一个累积值
KEY1 Date_ VAL1 CUMU_VAL2
K1 D1 1 0
K1 D2 1 1
K1 D3 0 2
K1 D4 1 0
K1 D5 1 1
因此,问题基本上是继续根据VAL1中的前一行在CUMU_VAL2列中将值加1,但是当VAL1列中的前一个值为零时,此和将重置。 基本上,如果您在excel中进行操作,则表示Cell(D3)的公式为
D3 = IF(C2>0, D2+1, 0)
我相信我应该可以这样做,但是当前一个值为零时,如何添加Case值,然后重设总和?
SELECT
a1.*,
SUM(a1.VAL1) OVER (PARTITION BY a1.KEY1 ORDER BY a1.Date_ ) AS CUMU_VAL2
FROM source_table a1
答案 0 :(得分:1)
您可以分配一个组-在给定行 之后为0的总和。然后使用count()
:
select t.KEY1, t.Date_, t.VAL1,
count(*) over (partition by key1, grp, (case when val1 = 0 then 0 else 1 end)
order by date_
) as cume_val1
from (select t.*,
sum(case when a.val1 = 0 then 1 else 0 end) over (partition by key1 order by date_ rows between 1 following and unbounded following) as grp
from source_table t
) t;
如果val1
仅取值0和1,则使用row_number()
代替count()
。
答案 1 :(得分:1)
我对@GordonLinoff的回答的修正是因为OP不太理解我的意思。
SELECT
t.KEY1, t.Date_, t.VAL1,
ROW_NUMBER() OVER (PARTITION BY key1, grp
ORDER BY Date_
)
- 1
AS CUMU_VAL2
FROM
(
SELECT
*,
SUM(
CASE WHEN val1 = 0 THEN 1 ELSE 0 END
)
OVER (
PARTITION BY key1
ORDER BY date_
)
AS grp
FROM
source_table
)
t;