我知道之前曾多次被问过,但我似乎遇到了一个奇怪的问题。
我正在尝试收集数据,以图表的形式显示每个货物每月欠款的总和。
我正在尝试将我的查询加入到几个月的临时表中,所以即使那个月没有数据,我仍然会得到图表的值为0.
我的代码:
INSERT INTO #DemurrageValuesExport
SELECT #Months.Month,
SUM(CASE
WHEN ISNULL(PD.PotentialDemurrageCost,0) < 0
THEN 0
ELSE ISNULL(PD.PotentialDemurrageCost,0)
END) AS [Potential Demurrage]
FROM dbo.Trip
RIGHT JOIN dbo.TripCargo
ON dbo.Trip.ID = dbo.TripCargo.TripID
RIGHT JOIN dbo.Cargo
ON dbo.TripCargo.CargoID = dbo.Cargo.ID
LEFT JOIN #Months
ON Month = PD.Berthed
LEFT JOIN dbo.PotentialDemurrageEvents AS PD
ON dbo.Trip.ID = PD.TripID
AND PD.Berthed BETWEEN @MonthStartDate AND @MonthEndDate
AND dbo.TripCargo.ID = PD.TripCargoID
WHERE dbo.Cargo.ID = @CargoID AND TripCargo.Export = 1
GROUP BY Month
这会循环过去12个月中的每一个,获得特定货物的价值。
问题出现了; ON Month = PD.Berthed
声称PD.Berthed
无法受约束。但是,我在查询中的其他位置使用了别名,它们不会导致问题。如果我删除临时表连接,查询执行正常。
有没有人知道发生了什么?或者失败了,实现我想要做的事情而不加入另一个月的桌子呢?
由于
答案 0 :(得分:3)
对临时表进行别名肯定会有助于清除问题,但我们还必须更改JOIN
的顺序,因为在您尝试加入#Months
时,PD
1}}别名尚未引入:
INSERT INTO #DemurrageValuesExport
SELECT m.Month,
SUM(CASE
WHEN ISNULL(PD.PotentialDemurrageCost,0) < 0
THEN 0
ELSE ISNULL(PD.PotentialDemurrageCost,0)
END) AS [Potential Demurrage]
FROM dbo.Trip
RIGHT JOIN dbo.TripCargo
ON dbo.Trip.ID = dbo.TripCargo.TripID
RIGHT JOIN dbo.Cargo
ON dbo.TripCargo.CargoID = dbo.Cargo.ID
LEFT JOIN dbo.PotentialDemurrageEvents AS PD
ON dbo.Trip.ID = PD.TripID
AND PD.Berthed BETWEEN @MonthStartDate AND @MonthEndDate
AND dbo.TripCargo.ID = PD.TripCargoID
LEFT JOIN #Months m
ON m.Month = PD.Berthed
WHERE dbo.Cargo.ID = @CargoID AND TripCargo.Export = 1
GROUP BY m.Month
完全混淆版本:
INSERT INTO #DemurrageValuesExport
SELECT m.Month,
SUM(CASE
WHEN ISNULL(PD.PotentialDemurrageCost,0) < 0
THEN 0
ELSE ISNULL(PD.PotentialDemurrageCost,0)
END) AS [Potential Demurrage]
FROM dbo.Trip t
RIGHT JOIN dbo.TripCargo tc
ON t.ID = tc.TripID
RIGHT JOIN dbo.Cargo c
ON tc.CargoID = c.ID
LEFT JOIN dbo.PotentialDemurrageEvents AS PD
ON t.ID = PD.TripID
AND PD.Berthed BETWEEN @MonthStartDate AND @MonthEndDate
AND tc.ID = PD.TripCargoID
LEFT JOIN #Months m
ON m.Month = PD.Berthed
WHERE c.ID = @CargoID AND tc.Export = 1
GROUP BY m.Month
答案 1 :(得分:1)
这是因为您在尝试引用它后加入了表。将连接移动到#Months之后
LEFT JOIN dbo.PotentialDemurrageEvents AS PD
-- ...
LEFT JOIN #Months
ON Month = PD.Berthed