2017-10-13 89 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()