sql计算基于配置单元中列的上一个值重置的累积和

wvyml7n5  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(399)

我试图用这样的东西创造一个累积值

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中这样做,那么单元格(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
swvgeqrz

swvgeqrz1#

我修改了戈登林诺夫的回答,因为他不太明白我的意思。

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;
ogq8wdun

ogq8wdun2#

您可以分配一个组,即给定行后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() .

相关问题