[英]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.