0

我有两张收入和支出表。我必须计算费用和收入的总和,并计算两者的差值。

我在用

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的收入之和减去每个人的费用。

我需要他们的个体差异。

4

1 回答 1

0

您可以使用子选择

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
于 2013-10-06T15:37:40.390 回答