简体   繁体   English

SQL查询查找列的总和

[英]SQL query to find sum of a column

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. 该表有两列:ID和金额。 The 'TotalAmount' should be created when the SQL script runs and hope, the rest of the sum is cleared from the above. SQL脚本运行时应创建'TotalAmount',希望从上面清除其余的金额。

How can I do the above sum?? 我该如何做? Please share ideas to do so. 请分享想法。 Thanks. 谢谢。

This is a cumulative sum. 这是一个累加的总和。 The ANSI standard method is as follows: ANSI标准方法如下:

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;

You didn't state your DBMS, so this is ANSI SQL: 您没有声明您的DBMS,所以这是ANSI SQL:

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

In SQL SERVER 2012 this Query is working fine. 在SQL SERVER 2012中,此查询工作正常。 Try This: 尝试这个:

SELECT 
   ID, 
   AMOUNT, 
   SUM(AMOUNT) 
   OVER(ORDER BY ID) AS TotalAmount
FROM 
   YourTable;
select id, amount, sum(amount) as totalAmount from table_name order by id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM