2012-04-23 52 views
1

我有2個表:SUM在加盟領域

團隊:

|-- id -- username --| 
|__ 1 __ user1 __| 
|__ 2 __ user2 __| 
|__ 3 __ user3 __| 

付款:

|-- id -- user_id -- amount --| 
|__ 1 __ 1  __ 1000 --| 
|__ 2 __ 1  __ 5000 --| 
|__ 3 __ 2  __ 3000 --| 
|__ 4 __ 1  __ 4500 --| 
|__ 5 __ 2  __ 1000 --| 

我想獲得用戶的支付總額。在單個查詢中。結果是這樣的:

|-- user_id -- username -- total_payment --| 
|__ 1  __ user1 __ 10500   --| 
|__ 2  __ user2 __ 4000   --| 

謝謝。

回答

3

如果你只想要user_id沒有username,沒有必要爲聯接,因爲在所有分組只需要在Payments發生對抗user_id

SELECT 
    user_id, 
    SUM(amount) AS total 
FROM Payments 
GROUP BY user_id 

編輯:的問題已經被編輯成包括在輸出的用戶名,因此使用下面的查詢 - 聯接是必要

如果你想加入用戶名,它是對FROMGROUP BY條款的簡單添加。

SELECT 
    Teams.user_id, 
    username, 
    SUM(amount) AS total 
FROM 
    Teams 
    /* LEFT JOIN used in case a user has no payments -- will still show in the list */ 
    LEFT JOIN Payments ON Teams.user_id = Payments.user_id 
GROUP BY 
    Teams.user_id, 
    Teams.username 
0
SELECT A.user_id,B.user_name,A.total AS total_payment 
FROM 
(
SELECT 
    user_id, 
    SUM(amount) AS total 
FROM Payments 
GROUP BY user_id 
) A, 
Teams B 
WHERE A.user_id = B.id;