获取一列的滚动SUM并将结果导入SQL

时间:2019-02-28 23:07:10

标签: sql sql-server

我有一个包含3列的表格:

ID   date           Amount
---------------------------
0    2019-01-25        500
3    2019-02-25       -200
4    2019-02-28        700
5    2019-02-28       -300

我想要一个查询,以在另一列中返回“金额”列的滚动总计:

ID   date           Amount     total amount
--------------------------------------------
0    2019-01-25        500              500
3    2019-02-25       -200              300
4    2019-02-28        700             1000
5    2019-02-28       -300              700

这是我的查询

   SELECT 
       ID,
       TrDate,
       Amount,
       SUM(CONVERT(FLOAT, [Amount])) AS 'total amount'                     
   FROM 
       [Transactions]

1 个答案:

答案 0 :(得分:3)

使用窗口功能SUM(...) OVER(...)

SELECT *, SUM(Amount) OVER(ORDER BY id) total_amount FROM mytable;

Demo on DB Fiddle

<pre>
ID | date                | Amount | total_amount
-: | :------------------ | -----: | -----------:
 0 | 25/01/2019 00:00:00 |    500 |          500
 3 | 25/02/2019 00:00:00 |   -200 |          300
 4 | 28/02/2019 00:00:00 |    700 |         1000
 5 | 28/02/2019 00:00:00 |   -300 |          700
</pre>

NB:如果您的SQLServer版本不支持窗口函数,则可以自联接表并使用聚合:

SELECT t.id, t.date, t.amount, SUM(t1.amount) total_amount
FROM mytable t
INNER JOIN mytable t1 ON t1.id <= t.id
GROUP BY t.id, t.date, t.amount