2017-03-15 53 views
0

我有2列的SQL表中的總金額,使用SQL找到捐贈給組織

organization_id, 
amount_donated 

我想回到一個新的表2列,

organization_id 
total_amount_donated 

我怎麼會去關於找到捐贈給每個組織的總金額?我想我必須使用GROUP BY,但我一直無法找到解決方案。

回答

1

你是對的,你確實想用GROUP BY。這是因爲您需要使用SUM聚合函數,並且通過使用GROUP BY organization_id,您將對每個組織的相應金額進行求和。

SELECT organization_id, SUM(amount_donated) AS total_amount_donated 
FROM your_table 
GROUP BY organization_id 

這是非常簡單的SQL,您應該可以親手製作教程或書籍,爲您介紹基本知識。 :)

0
select organisation_id,sum(amount_donated) as total_amt_donated from your_table 
group by organisation_id 

可以查詢這樣

0

您should't創建表,因爲它會創建重複的數據。相反,創建一個VIEW。

CREATE VIEW vw_total_donation 
AS 
SELECT organization_id, SUM(amount_donated) tot_donation 
FROM table1 
GROUP BY organization_id