2011-10-25 66 views
1

我有兩個表。表「用戶」包含user_id,user_name。表「交易」包含USER_ID,交易如何在一個表中顯示多行,並在一些計算後在另一個表中顯示一行

如: 表USER:

+---------+-----------+ 
| user_id | user_name | 
+---------+-----------+ 
| 1  | Ram  | 
| 2  | John  | 
+---------+-----------+ 

內幕交易

+---------+---------+--------------+ 
| user_id | type | transactions | 
+---------+---------+--------------+ 
| 1  | credit | 500   | 
| 1  | debit | 300   | 
| 2  | credit | 250   | 
| 1  | credit | 450   | 
| 2  | credit | 100   | 
| 1  | debit | 250   | 
| 2  | debit | 50   | 
+---------+---------+--------------+ 

我想將所有的信貸量來顯示結果並扣除所有借方發生額如下圖所示:

+-----------+--------------+-------------+-------------+ 
| user_name | Total Credit | Total debit | Grand Total | 
+-----------+--------------+-------------+-------------+ 
| Ram  | 950   | 550   | 400   | 
| John  | 350   | 50   | 300   | 
+-----------+--------------+-------------+-------------+ 

我該怎麼做?

+0

忘記整齊地格式化我的問題的方法不止一種。 – user1010966

回答

1

這裏的查詢:

SELECT 
    u.user_name, 
    SUM(IF(t.type = 'credit', t.transactions, 0)) AS totalcredit, 
    SUM(IF(t.type = 'debit', t.transactions, 0)) AS totaldebit, 
    SUM(IF(t.type = 'credit', -1, 1) * t.transactions) AS total 
FROM 
    transactions t 
INNER JOIN 
    users u 
ON 
    u.user_id = t.user_id 
GROUP BY 
    u.user_name 
+0

這不是一個好主意,同時命名錶和其中一個字段「交易」 –

+0

我測試了你的代碼。但是...我想顯示所有用戶名,即使他們沒有任何條目在交易表中。你能幫 – user1010966

+0

剛剛修改Nedret雷傑普與左邊的答案JOIN和倒「交易」和「用戶」爲了 選擇 u.user_name, SUM(IF(t.type =「信用」,t.transactions ,0))AS totalcredit, SUM(IF(t.type ='debit',t.transactions,0))AS totaldebit, SUM(IF(t.type ='credit',-1,1)* t .transactions)AS總 FROM 用戶ü LEFT JOIN 交易噸 ON u.user_id = t.user_id GROUP BY u.user_name 感謝您的所有答案 – user1010966

0

嘗試以下查詢

SELECT u.user_name, 
    SUM((IF(c.type = "credit", c.transactions, (0)))) AS total_credit, 
    SUM((IF(c.type = "debit", c.transactions, (0)))) AS total_debit, 
    SUM(IF(c.type = "credit", c.transactions, (0 - c.transactions))) AS grand_total 
FROM 
    credit_debit AS c 
INNER JOIN user_details AS u 
    ON c.user_id = u.user_id 
GROUP BY 
    u.user_id 

假設只有借記卡和信用卡類型會在那裏,如果任何其它類型的會來,那麼你需要改變的代碼。

2

像往常一樣,有剝皮的貓!:

SELECT u.user_name, t2.TotCredit, t1.TotDebit, (t2.TotCredit-t1.TotDebit) AS "GrandTotal"  
    FROM (SELECT user_id, SUM(transactions) AS "TotCredit" FROM transactiONs WHERE Type='Credit'GROUP BY user_id) AS t2  
LEFT OUTER JOIN  
    (SELECT user_id, SUM(transactions) AS "TotDebit" FROM transactiONs WHERE Type='Debit'GROUP BY user_id) AS t1  
    ON t1.user_id = t2.user_id  
LEFT OUTER JOIN  
    (SELECT user_name,user_id FROM user GROUP BY user_name) AS u  
    ON u.user_id = t2.user_id  

GROUP BY t2.user_id  
ORDER BY t2.user_id 
相關問題