我有2张桌子的收入和支出。我必须计算费用和收入的总和,并计算两个总和的差异。
我正在使用
SELECT (SUM(a.Amount)-(SELECT SUM(i.Amount)
FROM incomes i GROUP BY i.UserId)) Expense,
a.UserId FROM amount a GROUP BY a.UserId
目前只有收入表中的UserId,所以当我执行查询时,它会获取UserId收入的总和并减去每个人的开支。
我需要他们的个人差异。
答案 0 :(得分:0)
您可以使用subselect
SELECT (q.Amount - q.Expense) AS `diff` FROM
(
(SELECT (SUM(a.Amount)
FROM amount a GROUP BY a.UserId) AS `Amount`,
(SELECT SUM(i.Amount)
FROM incomes i GROUP BY i.UserId) AS Expense,
) q
或加入
SELECT (q.Amount - q.Expense) AS `diff` FROM
(
SELECT SUM(a.Amount) AS `Amount` ,SUM(i.Amount) AS `Expense`
FROM amount
JOIN incomes i ON ( a.UserId=i.UserId)
GROUP BY i.UserId
) q
或者您可以尝试FULL OUTER JOIN,因为它们不存在,但您仍然可以使用UNION
SELECT (q.Amount - q.Expense) AS `diff` FROM
(
(SELECT (SUM(a.Amount) AS `Amount` , NULL AS `Expense`
FROM amount a GROUP BY a.UserId)
UNION ALL
(SELECT NULL AS `Amount`, SUM(i.Amount) AS Expense
FROM incomes i GROUP BY i.UserId)
) q