对Join和Group By感到困惑

时间:2017-10-13 09:10:07

标签: sql sql-server

我有这个查询

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中没有包含GROUP BY)它会改变我的子选择的行数,结果是错。

如何在不影响成本计算的情况下返回此字段?

1 个答案:

答案 0 :(得分: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()