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  |

我正在寻找一种方法来使用一个查询并检索每个用户的平衡。

当必须将金额添加到费用中并从收入中减去时,困难的部分就来了。

这将是结果表:

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

3 回答 3

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 演示

于 2012-08-08T23:50:04.903 回答
1

这对单个组最简单,方法是:

select user_id,
       sum(case when type = 'income' then amount else - amount end) as balance
from t
group by user_id
于 2012-08-09T01:31:18.630 回答
0

您可以有 2 个子查询,每个子查询按 id 分组:一个汇总收入,另一个汇总支出。然后你可以将它们连接在一起,这样每一行都有一个 id、费用总和和收入总和,你可以从中轻松计算余额。

于 2012-08-08T23:47:43.687 回答