2017-07-06 55 views
0

我想了解爲什麼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

這很可能數據問題。 'revenueC'和'revenueD'通過(左)外連接連接,這意味着如果它們的連接條件不匹配,它們將返回一行空值。 – RBarryYoung

+0

tpth是LEFT JOINed,WHERE子句反對tpth,它變成了INNER JOIN。 – Wendy

+0

當您嘗試運行CTE的全部內容(即定義)時會發生什麼? – Eli

回答

0

是左連接,系統就會顯示聯接(tptvehicle,tptHeader和tptVehicleRevenueDaily)的左手側行,即使在嵌套查詢不存在的行...如果將其更改爲內連接,它將只顯示這些行存在的行,但是這將EXCLUDE在這個嵌套查詢中沒有行的車輛(它們當前在那些列中顯示爲空值),你想要這個嗎?...