SQL query to find sum of a column

时间:2016-05-17 11:10:13

标签: sql

I have a table where I have to get the output as follows:

ID - amount - TotalAmount  
1  - 400    - 400  
2 -  600    - 1000  
3 -  400    - 1400  

The table has two columns: ID & amount. The 'TotalAmount' should be created when the SQL script runs and hope, the rest of the sum is cleared from the above.

How can I do the above sum?? Please share ideas to do so. Thanks.

4 个答案:

答案 0 :(得分:3)

This is a cumulative sum. The ANSI standard method is as follows:

select id, amount, sum(amount) over (order by id) as TotalAmount
from t;

Most, but not all databases, support this syntax.

The above is the "right" solution. If your database doesn't support it, then a correlated subquery is one method:

select t.id, t.amount,
       (select sum(t2.amount) from t t2 where t2.id <= t.id) as TotalAmount
from t;

答案 1 :(得分:2)

You didn't state your DBMS, so this is ANSI SQL:

select id, amount, 
       sum(amount) over (order by id) as totalamount
from the_table

答案 2 :(得分:0)

在SQL SERVER 2012中,此查询工作正常。试试这个:

SELECT 
   ID, 
   AMOUNT, 
   SUM(AMOUNT) 
   OVER(ORDER BY ID) AS TotalAmount
FROM 
   YourTable;

答案 3 :(得分:0)

select id, amount, sum(amount) as totalAmount from table_name order by id;