联接使用不当 - 如何纠正

时间:2017-07-06 14:41:17

标签: sql-server

我想了解为什么revenue.RevC和revenue.RevD显示为Null,即使我在另一个选项卡上运行单独的嵌套时它会带来信息。

你能否发现我在加入时所犯的错误,导致我无法在[rev col]和[rev del]列中获取任何数据。我相信这是由于使用了左连接。我对么?

 with CTE as 
 (
select count(tpt1.MovConID) as [Collections], 
count(tpt2.MovConID) as [Count of Del],
sum (c1.[Chargeable Weight]) as [Total Col Chg Wt],
sum(c2.[Chargeable Weight]) as [Total Del Chg Wt],
revenueC.RevC as [Rev Col],
revenueD.RevD as [Rev Del]
from tptvehicle tptv
left JOIN tptHeader tpth ON tpth.VehicleID = tptV.VehicleID
left JOIN tptVehicleRevenueDaily tptrevenue on tptrevenue.VehicleReg = tptv.RegNo
left Join (select tpth.RunReference, tptV.VehicleID, sum(tptvehicle.Amount) as RevC from tptVehicleRevenueDaily tptvehicle 
       inner join tptVehicle tptv on tptv.RegNo = tptvehicle.VehicleReg
       inner join tptHeader tptH on tptH.VehicleID = tptv.VehicleID
       inner join tptDetails tpt on tpt.RunID = tptH.RunID where tpt.RunType = 'C'
       group by tpth.RunReference, tptv.VehicleID) revenueC on revenueC.RunReference = Tpth.RunReference
Left Join (select tpth.RunReference, tptV.VehicleID, sum(tptvehicle.Amount) as RevD from tptVehicleRevenueDaily tptvehicle 
       inner join tptVehicle tptv on tptv.RegNo = tptvehicle.VehicleReg
       Inner join tptHeader tptH on tptH.VehicleID = tptv.VehicleID
       Inner join tptDetails tpt on tpt.RunID = tptH.RunID where tpt.RunType = 'D'
       group by tpth.RunReference, tptv.VehicleID) revenueD on revenueD.VehicleID = TptV.VehicleID
 LEFT JOIN tptDetails tpt1 ON tpt1.RunID = tptH.RunID and tpt1.RunType = 'C'
 LEFT JOIN cgtConsignment c1 on c1.[Consignment Reference] = tpt1.MovConID
 LEFT JOIN tptDetails tpt2 on tpt2.RunID = tptH.RunID and tpt2.RunType = 'D'
 LEFT Join cgtConsignment c2 on c2.[Consignment Reference] = tpt2.MovConID
 where tpth.RunReference like 'bham-%' and
 tptH.JourneyDate >= @StartDate and
          tpth.JourneyDate <= @EndDate 
          Group by revenueC.RevC, revenueD.RevD
 )
Select cte.collections, cte.[count of del], cte.[Total Col Chg Wt], cte.[Total Del Chg Wt], cte.[Rev Col], cte.[Rev Del]
from CTE

1 个答案:

答案 0 :(得分:0)

是的,左连接将显示连接左侧的行(tptvehicle,tptHeader和tptVehicleRevenueDaily),即使嵌套查询中不存在任何行...如果将其更改为内连接,它将显示只有那些存在的行,但是这将排除在这个嵌套查询中没有行的车辆(当前在这些列中显示空值),你想要这个吗?...