2011-10-25 14 views
1

私は2つのテーブルを持っています。テーブル "user"には、user_id、user_nameが含まれています。表 "トランザクション" のuser_idが含まれ、取引いくつかの計算の後に別のテーブルに1行のテーブルを複数行表示する方法

例: 表USER:

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

TABLE取引

+---------+---------+--------------+ 
| 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

テーブルとそのフィールド "transactions"の両方に名前を付けることは良い考えではありません –

+0

私はあなたのコードをテストしました。しかし...トランザクションテーブルにエントリがなくても、すべてのユーザー名を表示したいと思います。あなたは – user1010966

+0

ちょうどJOINをLEFTとNedretレジェップの答えを修正し、「取引」と「ユーザー」ため (IF(t.type =「クレジット」を u.user_name、 SUMを選択して、t.transactionsを逆に助けてもらえ、0))AS totalcredit、 SUM(IF(t.type = 'デビット'、t.transactions、0))AS totaldebit、 SUM(IF(t.type = 'credit'、-1,1)* t .transactions)合計 FROMユーザーなどuが LEFT u.user_id = t.user_id GROUP BY u.user_name ON トランザクションTをJOIN すべての回答ありがとう – 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 
関連する問題