我正在查询 3 个表格汽车、费用和收入:
SELECT c.CarMake, c.CarType,
(SUM(i.IncomeKMEnd -i.IncomeKMStart)) AS TotalKms,
MAX(i.IncomeKMEnd) as EndingKMs,
CONVERT(varchar(10), CONVERT(int,100.0*(SUM(i.IncomePrice) - SUM(e.ExpenseAmount))/c.CarBuyPrice)) +'%' as IncomePercentage,
SUM(CASE WHEN e.PaymentType LIKE '%extra%' THEN e.ExpenseAmount ELSE 0 END) AS ExpenseSum
FROM (Cars AS c
INNER JOIN Incomes as i ON c.CarID = i.CarID AND (i.IncomeDateFrom BETWEEN '20130101' AND '20140101'))
INNER JOIN Expenses as e ON i.CarID = e.CarID AND (e.ExpenseDateFrom BETWEEN '20130101' AND '20140101')
GROUP BY c.CarType, c.CarMake, c.CarBuyPrice
Cars 表中有一辆汽车,它在 Income 表中被引用 3 次,在 Expenses 表中被引用 2 次。此查询在未分组时返回 6 行并将费用和收入相加 6 次。有没有办法让它正确地总结收入和支出?