0

我正在查询 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 次。有没有办法让它正确地总结收入和支出?

4

2 回答 2

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
于 2013-09-16T20:21:28.747 回答
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
于 2013-09-16T21:48:33.320 回答