繁体   English   中英

SQL查询查找列的总和

[英]SQL query to find sum of a column

我有一个表,必须在其中获取如下输出:

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

该表有两列:ID和金额。 SQL脚本运行时应创建'TotalAmount',希望从上面清除其余的金额。

我该如何做? 请分享想法。 谢谢。

这是一个累加的总和。 ANSI标准方法如下:

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

大多数(但不是全部)数据库都支持此语法。

以上是“正确的”解决方案。 如果您的数据库不支持它,则关联子查询是一种方法:

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

您没有声明您的DBMS,所以这是ANSI SQL:

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

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

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