2012-08-08 50 views
1

請幫助,我有一個表像這樣我的用戶的平衡:獲取在同一個表

| ID | userId | amount | type | 
------------------------------------- 
| 1 |  10 | 10  | expense | 
| 2 |  10 | 22  | income | 
| 3 |  3 | 25  | expense | 
| 4 |  3 | 40  | expense | 
| 5 |  3 | 63  | income | 

我正在尋找一種方式來使用一個查詢和retrive每個用戶的平衡。

困難的部分來自於金額必須加在費用上而減去收入。

這將是結果表:

| userId | balance | 
-------------------- 
| 10 | 12  | 
| 3 | -2  | 

回答

1

這是最容易做的單組通過:

select user_id, 
     sum(case when type = 'income' then amount else - amount end) as balance 
from t 
group by user_id 
+0

這也適用,謝謝Gordon – 2012-08-09 14:09:23

0

你可以有2子查詢,通過每個ID分組:一個資金收入,其他的費用。然後,您可以將它們結合在一起,以便每行都有一個ID,即費用總額和收入總和,您可以從中輕鬆計算餘額。

4

你需要使用子查詢然後拿到incomeexpense每個彙總以後加入他們,你可以subtract expense from income

SELECT a.UserID, 
     (b.totalIncome - a.totalExpense) `balance` 
FROM 
(
    SELECT userID, SUM(amount) totalExpense 
    FROM myTable 
    WHERE type = 'expense' 
    GROUP BY userID 
) a INNER JOIN 
(
    SELECT userID, SUM(amount) totalIncome 
    FROM myTable 
    WHERE type = 'income' 
    GROUP BY userID 
) b on a.userID = b.userid 

SQLFiddle Demo

+0

謝謝你親愛的先生 – 2012-08-09 00:02:05

+0

不客氣Gaddiel :) – 2012-08-09 00:03:00

+0

這個查詢實際上不適用於只有收入或只有開銷的用戶。 – 2012-08-09 01:31:52