请帮忙,我有一张这样的表:
| 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 |
答案 0 :(得分:4)
您需要使用 子查询 获取income
和expense
的每个总计,然后再使用 join 他们可以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
答案 1 :(得分:1)
这对于单个群组来说最容易做到:
select user_id,
sum(case when type = 'income' then amount else - amount end) as balance
from t
group by user_id
答案 2 :(得分:0)
您可以有2个子查询,每个子查询按ID分组:一个是收入的总和,另一个是费用。然后你可以将它们加在一起,这样每行都有一个id,即费用的总和和收入的总和,你可以从中轻松计算余额。