当我尝试在SSMS 2012 Express上执行以下脚本时:
SELECT ItemID, ItemPrice, DiscountAmount, Quantity,
ItemPrice * Quantity AS PriceTotal,
DiscountAmount * Quantity AS DiscountTotal,
Quantity * (ItemPrice - DiscountAmount) AS ItemTotal
FROM OrderItems
WHERE ItemTotal > 500
ORDER BY ItemTotal DESC
“Intellisense”在WHERE子句中引用“ItemTotal”和“仅在WHERE子句中”表示“无效列名称”。如果我注释掉或删除WHERE子句,即使在ORDER BY子句中也调用了“ItemTotal”,它也能正常工作。
请帮忙。
非常感谢。
答案 0 :(得分:2)
这是因为WHERE
和ORDER BY
在执行期间的两个不同时间进行评估:
别名(即 AS 子句后面的名称)是对此“表格”列的某种“重命名”,它将与 SELECT 一起显示。这意味着在计算 WHERE 子句时它们尚不存在。
ORDER BY 在构建table
后发生,因此系统现在知道别名引用的列。
要做你想做的事,你必须写:
SELECT ItemID, ItemPrice, DiscountAmount, Quantity,
ItemPrice * Quantity AS PriceTotal,
DiscountAmount * Quantity AS DiscountTotal,
Quantity * (ItemPrice - DiscountAmount) AS ItemTotal
FROM OrderItems
WHERE Quantity * (ItemPrice - DiscountAmount) > 500 --here SQL doesn't know what "ItemTotal" is...
ORDER BY ItemTotal DESC -- but at this stage it does understand !
答案 1 :(得分:0)
Select * from
( SELECT ItemID,
ItemPrice,
DiscountAmount,
Quantity,
ItemPrice * Quantity AS PriceTotal,
DiscountAmount * Quantity AS DiscountTotal,
Quantity * (ItemPrice - DiscountAmount) AS ItemTotal
FROM OrderItems
) as t
WHERE ItemTotal > 500
ORDER BY ItemTotal DESC
希望这有帮助
快乐编码