2017-10-13 73 views
0

我有這個疑問困惑加入和GROUP BY

SELECT (T1.FirstDayOfMonth 
     , T1.VehicleType 
     , SUM(T1.Cost-T2.Cost) 
    ) 
FROM (SELECT FirstDayOfMonth 
      , VehicleType 
      , [Cost] = Cost*Rate 
     FROM fnCalculationData(@CalculationId1) 
     GROUP BY FirstDayOfMonth, VehicleType 
    ) AS T1 
    LEFT JOIN (SELECT FirstDayOfMonth 
        , VehicleType 
        , [Cost] = Cost*Rate 
       FROM fnCalculationData(@CalculationId2) 
       GROUP BY FirstDayOfMonth, VehicleType 
       ) AS T2 ON T1.VehicleType = T2.VehicleType 
GROUP BY T1.FirstDayOfMonth, T1.VehicleType 

但我意識到我可能需要以後篩選我的結果在另一個領域,RegistrationTypeId,所以我把它添加到我的選擇:

SELECT (T1.FirstDayOfMonth 
     , T1.VehicleType 
     , T1.RegistrationTypeId 
     , SUM(T1.Cost - T2.Cost) 
     ) 
FROM (SELECT FirstDayOfMonth 
      , VehicleType 
      , RegistrationTypeId 
      , [Cost] = Cost*Rate 
     FROM fnCalculationData(@CalculationId1) 
     GROUP BY FirstDayOfMonth, VehicleType, RegistrationTypeId 
    ) AS T1 LEFT JOIN (SELECT FirstDayOfMonth 
           , VehicleType 
           , RegistrationTypeId 
           , [Cost] = Cost*Rate 
         FROM fnCalculationData(@CalculationId2) 
         GROUP BY FirstDayOfMonth, VehicleType, RegistrationTypeId 
         ) AS T2 ON T1.VehicleType = T2.VehicleType 
GROUP BY T1.FirstDayOfMonth, T1.VehicleType, T1.RegistrationTypeId 

但是這會給我錯誤的成本價值(即使我不包括RegistrationTypeId在我的主要SELECT s GROUP BY)它改變了我的子選擇的行數,結果是錯誤的。

如何在不影響成本計算的情況下返回此字段?

+5

示例數據請與您所得到的和您的期望。 – wast

+0

您正在使用哪種SQL Server版本?似乎你需要同時收集和詳細的信息,而窗口功能可以在這裏完成工作。當然也可以進行次選。 –

+0

爲什麼所有括號? – JohnHC

回答

0

我認爲你需要包括所有GROUP BY鍵爲JOIN鍵:

select T1.FirstDayOfMonth, T1.VehicleType, T1.RegistrationTypeId, 
     (T1.Cost - coalesce(T2.Cost, 0))) 
from (Select FirstDayOfMonth, VehicleType, RegistrationTypeId, [Cost] = 
Cost*Rate 
     from fnCalculationData(@CalculationId1) 
     group by FirstDayOfMonth, VehicleType, RegistrationTypeId 
    ) t1 left join 
    (Select FirstDayOfMonth, VehicleType, RegistrationTypeId, [Cost] = 
Cost*Rate 
     from fnCalculationData(@CalculationId2) 
     group by FirstDayOfMonth, VehicleType, RegistrationTypeId 
    ) t2 
    on t1.FirstDayOfMonth = t2.FirstDayOfMonth and 
     t1.VehicleType = t2.VehicleType and 
     t1.RegistrationTypeId = t2.RegistrationTypeId; 

您應該不需要外部查詢聚集。如果第二個表中沒有匹配,則確實需要coalesce()