0

我正在尝试用这样的东西创建一个累积值

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)

我相信我应该能够做到这样,但是当先前的值为零时如何添加案例然后重置总和?

SELECT
   a1.*,
       SUM(a1.VAL1) OVER (PARTITION BY a1.KEY1 ORDER  BY a1.Date_ ) AS CUMU_VAL2
FROM source_table a1
4

2 回答 2

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().

于 2018-09-24T21:38:03.990 回答
1

My amendment to @GordonLinoff's answer as the OP didn't quite understand what I meant.

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;
于 2018-09-24T22:08:39.030 回答