SUMIF case when SQL - 基于行值的总和

SUMIF case when SQL - sum based on row value

我有一个包含 A、B、C 列的数据集。我想对 C 求和,其中 B 中的值大于等于 B 中的其余值。我尝试了一个 Sum 的情况,但是似乎无法获得使用行值的条件。有什么想法吗?

输入:

A|B|C
1|1|1
1|2|1
1|3|1
2|1|0
2|2|1
2|3|0

想要的输出:

A|B|C|Output
1|1|1|3
1|2|1|2
1|3|1|1
2|1|0|1
2|2|1|1
2|3|0|0

代码已尝试但由于条件问题无法运行

SUM(case when B>=B then C end) over(partition by A) as Output

输出计算:

A|B|C|Output calculation                                  |Excel calculation                | Output 
1|1|1|Sum all values in Col C where values in B>=1 and A=1 | =SUMIFS(C:C,B:B,">="&B2,A:A,A2) |=3
1|2|1|Sum all values in Col C where values in B>=2 and A=1 | =SUMIFS(C:C,B:B,">="&B3,A:A,A3) |=2
1|3|1|Sum all values in Col C where values in B>=3 and A=1 | =SUMIFS(C:C,B:B,">="&B4,A:A,A4) |=1
2|1|0|Sum all values in Col C if values in B>=1 and A=2    | =SUMIFS(C:C,B:B,">="&B5,A:A,A5) |=1
2|2|1|Sum all values in Col C if values in B>=2 and A=2    | =SUMIFS(C:C,B:B,">="&B6,A:A,A6) |=1
2|3|0|Sum all values in Col C if values in B>=3 and A=2    | =SUMIFS(C:C,B:B,">="&B7,A:A,A7) |=0

我认为您需要自连接或相关子查询:

select t.*,
       (select sum(t2.c)
        from t t2
        where t2.a = t.a and t2.b > t.b
       ) as output
from t;

您的逻辑可能等同于 cb 值的反向求和:

select t.*,
       sum(c) over (partition by a order by b desc)
from t;

但是,我不确定您想如何处理具有相同 b 值的行。

考虑以下方法

select *,
  sum(c) over(partition by a order by b desc) output
from data    

如果应用于您问题中的示例数据 - 输出为

同时,我注意到与如何处理 B=B 案例相关的问题存在一些差异,在 excel 公式中它说 where values in B>... 而在输出示例和代码中尝试它是 when B>=B then 到目前为止,这是所有当前提供的答案所做的。
所以,下面“做”B>B逻辑(并且可以很容易地修改为任何滞后值)

select *,
  sum(c) over(partition by a order by b range between 1 following and unbounded following) output
from data    

有输出

select * , sum(C) over (partition by A order by B desc)
from data
order by A,B
 a |  b |  c | sum
-: | -: | -: | --:
 1 |  1 |  1 |   3
 1 |  2 |  1 |   2
 1 |  3 |  1 |   1
 2 |  1 |  0 |   1
 2 |  2 |  1 |   1
 2 |  3 |  0 |   0

db<>fiddle here