SQl汇总表:一列与另一列的部分总和[重复]

时间:2020-12-28 07:57:19

This question already has an answer here:

这个问题在这里已有答案:

I want to make a table in SQL, based on a table that looks like this

我想基于一个看起来像这样的表在SQL中创建一个表

Table 1

row    cost
1       25
2       15
3       10
4       12
...     ...

In the new table for each row the column SUM is the sum of all cost whose rows are less than or equal to the one in the new table.

在每行的新表中,列SUM是其行小于或等于新表中的行的所有成本的总和。

Table 2

row    SUM
1       25 
2       40 is the sum of row 1 and 2 from Table 1
3       50 is the sum of row 1, 2 and 3 from Table 1
4       62 is the sum of row 1, 2, 3 and 4 from Table 1
...     ...

Do you have any idea how to do this in the most efficient way without creating a lot of joins?

您是否知道如何在不创建大量连接的情况下以最有效的方式执行此操作?

1 个解决方案

#1


0  

You want a cumulative sum:

你想要一个累积总和:

select row, sum(cost) over (order by row) as running_sum
from table1;

#1


0  

You want a cumulative sum:

你想要一个累积总和:

select row, sum(cost) over (order by row) as running_sum
from table1;