嵌套的计算列“无效列名”错误(T-SQL列别名)
问题描述:
我已创建3个计算列作为别名,然后使用别名列计算总成本。这是查询:嵌套的计算列“无效列名”错误(T-SQL列别名)
SELECT TOP 1000 [Id]
,[QuantityOfProduct]
,[Redundant_ProductName]
,[Order_Id]
,(CASE
WHEN [PriceForUnitOverride] is NULL
THEN [Redundant_PriceForUnit]
ELSE
[PriceForUnitOverride]
END
) AS [FinalPriceForUnit]
,(CASE
WHEN [QuantityUnit_Override] is NULL
THEN [Redundant_QuantityUnit]
ELSE
[QuantityUnit_Override]
END
) AS [FinalQuantityUnit]
,(CASE
WHEN [QuantityAtomic_Override] is NULL
THEN [Redundant_QuantityAtomic]
ELSE
[QuantityAtomic_Override]
END
) AS [Final_QuantityAtomic]
--***THIS IS WHERE THE QUERY CREATES AN ERROR***--
,([QuantityOfProduct]*[FinalPriceForUnit]*
([Final_QuantityAtomic]/[FinalQuantityUnit])) AS [Final_TotalPrice]
FROM [dbo].[ItemInOrder]
WHERE [IsSoftDeleted] = 0
ORDER BY [Order_Id]
控制台返回此错误消息:
Msg 207, Level 16, State 1, Line 55
Invalid column name 'FinalPriceForUnit'.
Msg 207, Level 16, State 1, Line 55
Invalid column name 'Final_QuantityAtomic'.
Msg 207, Level 16, State 1, Line 55
Invalid column name 'FinalQuantityUnit'.
如果我删除了“AS [Final_TotalPrice]”别名计算列,没有出现错误,但我需要的总价格。我该如何解决这个问题?好像其他别名在达到Final_TotalPrice时尚未创建。
答
您不能在同一select中使用表别名。正常的解决方案是CTE或子查询。但是,SQL Server也提供APPLY
。 (Oracle还支持APPLY
和其他数据库如Postgres的支持横向联接使用LATERAL
关键字)。
我是这样解决的,因为你可以创建任意嵌套的表达式,并不必担心缩进:
SELECT TOP 1000 io.Id, io.QuantityOfProduct, io.Redundant_ProductName,
io.Order_Id,
x.FinalPriceForUnit, x.FinalQuantityUnit, x.Final_QuantityAtomic,
(x.QuantityOfProduct * x.FinalPriceForUnit * x.Final_QuantityAtomic/x.FinalQuantityUnit
) as Final_TotalPrice
FROM dbo.ItemInOrder io OUTER APPLY
(SELECT COALESCE(PriceForUnitOverride, Redundant_PriceForUnit) as FinalPriceForUnit,
COALESCE(QuantityUnit_Override, Redundant_QuantityUnit) as FinalQuantityUnit
COALESCE(QuantityAtomic_Override, Redundant_QuantityAtomic) as Final_QuantityAtomic
) x
WHERE io.IsSoftDeleted = 0
ORDER BY io.Order_Id ;
注:
- 我没有找到
[
和]
帮我读或写的所有查询。 -
COALESCE()
比您的CASE
陈述简单得多。 - 随着
COALESCE()
你可能会考虑只是把COALESCE()
表达式在最后的计算。
答
您不能在同一选择中使用别名。你可以做的是找到子查询中的值,然后在表达式中使用它(或者可以在表达式中重复整个case语句)。此外,请使用COALESCE
来代替CASE
。
select t.*,
([QuantityOfProduct] * [FinalPriceForUnit] * ([Final_QuantityAtomic]/[FinalQuantityUnit])) as [Final_TotalPrice]
from (
select top 1000 [Id],
[QuantityOfProduct],
[Redundant_ProductName],
[Order_Id],
coalesce([PriceForUnitOverride], [Redundant_PriceForUnit]) as [FinalPriceForUnit],
coalesce([QuantityUnit_Override], [Redundant_QuantityUnit]) as [FinalQuantityUnit],
coalesce([QuantityAtomic_Override], [Redundant_QuantityAtomic]) as [Final_QuantityAtomic]
from [dbo].[ItemInOrder]
where [IsSoftDeleted] = 0
order by [Order_Id]
) t;
整洁的解决方案,再加上你包括APPLY – Luther