如何在SQL服务器中获取累计和(Z=Z+A+B-C)
How to get cumulative sum in SQL Server (Z=Z+A+B-C)
我想在 table ( Commul_table) 和 SQL 中创建累计和,例如
Z=Z+ (A+B-C )
在这种情况下,您可以将 analytic function
与 rows unbounded preceding
一起使用(以获取当前行之前的总和值)
Select id, A,B,C,sum(A+B-C) over(order by Id rows unbounded preceding) as Z
From Table
它仍然是一个累计总和,只是基于对三列的计算:
sum(a+b-c) over (order by Id rows unbounded preceding)
我的回答是要指出大多数数据库不需要 window frame 子句。假设 id
是唯一的:
select ct.*, sum(a + b - c) over (order by id) as z
from Commul_table;
如果id
可以重复,请说明您想要的结果。以上还假设 a
、b
和 c
永远不会是 NULL
。如果可以,那么您想用 0
代替它们:
select ct.*,
sum(coalesce(a, 0) + coalesce(b, 0) - coalesce(c, 0)) over (order by id) as z
from Commul_table;
我想在 table ( Commul_table) 和 SQL 中创建累计和,例如 Z=Z+ (A+B-C )
在这种情况下,您可以将 analytic function
与 rows unbounded preceding
一起使用(以获取当前行之前的总和值)
Select id, A,B,C,sum(A+B-C) over(order by Id rows unbounded preceding) as Z
From Table
它仍然是一个累计总和,只是基于对三列的计算:
sum(a+b-c) over (order by Id rows unbounded preceding)
我的回答是要指出大多数数据库不需要 window frame 子句。假设 id
是唯一的:
select ct.*, sum(a + b - c) over (order by id) as z
from Commul_table;
如果id
可以重复,请说明您想要的结果。以上还假设 a
、b
和 c
永远不会是 NULL
。如果可以,那么您想用 0
代替它们:
select ct.*,
sum(coalesce(a, 0) + coalesce(b, 0) - coalesce(c, 0)) over (order by id) as z
from Commul_table;