我正在查询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表中有一辆车,它在Incomes表中被反映了3次,在Expenses表中有2次。未分组时,此查询返回6行,并将费用和收入相加6次。有没有办法让它正确地计算收入和支出?
答案 0 :(得分:1)
执行此操作的一种方法是不加入另一个表,而是将子信息中的信息拉出来。例如:
SELECT c.CarMake, c.CarType,
(SELECT SUM(IncomePrice) FROM Incomes WHERE CarID = c.CarID and (IncomeDateFrom BETWEEN '20130101' AND '20140101')) SumPrice
FROM Cars AS c
答案 1 :(得分:1)
如果您使用的是SQL Server 2005或更新版本,那么最好使用APPLY子句。此外,我认为你应该考虑到特定CarId的收入和支出是空的。
SELECT c.CarMake,
c.CarType,
i.TotalKms,
i.EndingKMs,
CONVERT(varchar(10), CONVERT(int,100.0*( isnull( i.IncomePriceTotal, 0) - isnull( e.ExpenseAmountTotal, )) / c.CarBuyPrice)) +'%' as IncomePercentage,
e.ExpenseSum
FROM Cars c
OUTER APPLY
(
SELECT SUM(i.IncomeKMEnd -i.IncomeKMStart) AS TotalKms,
MAX(i.IncomeKMEnd) as EndingKMs,
SUM(i.IncomePrice) as IncomePriceTotal
FROM Incomes i
WHERE i.CarID = c.CarID
AND i.IncomeDateFrom BETWEEN '20130101' AND '20140101'
) i
OUTER APPLY
(
SELECT SUM(e.ExpenseAmount) as ExpenseAmountTotal,
SUM(CASE WHEN e.PaymentType LIKE '%extra%' THEN e.ExpenseAmount ELSE 0 END) AS ExpenseSum
FROM Expenses e
WHERE e.CarID = c.CarID
AND e.ExpenseDateFrom BETWEEN '20130101' AND '20140101'
) e