在一些计算之后,如何在表中显示多行,在另一个表中显示一行

时间:2011-10-25 05:44:34

标签: mysql select left-join multiple-tables

我有两张桌子。表“user”包含user_id,user_name。表“交易”包含user_id,transactions

例如: 表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         |
+-----------+--------------+-------------+-------------+

我该怎么做?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

假设只有借记和贷记类型,如果有其他类型,那么你需要更改代码。