SELECT
o.OrderID, ProductName, OrderDate, ItemPrice, TaxAmount,
DiscountAmount, DiscountAmount - ItemPrice AS FinalTotal,
Quantity, ShipDate,FinalTotal * Quantity AS ItemTotal
FROM
Orders AS o
JOIN
OrderItems AS oi ON o.OrderID = oi.OrderID
JOIN
Products AS p ON oi.ProductID = p.ProductID;
这是我的代码,它一直说无效的列名称' FinalTotal'。我在这里做错了什么?
答案 0 :(得分:5)
你不能在同一个查询级别上使用列别名。
在计算ItemTotal
时使用FinalToal的完整表达式SELECT o.OrderID, ProductName, OrderDate, ItemPrice, TaxAmount, DiscountAmount,
DiscountAmount - ItemPrice AS FinalTotal,
Quantity, ShipDate,
(DiscountAmount - ItemPrice) * Quantity AS ItemTotal
FROM Orders AS o JOIN OrderItems AS oi
ON o.OrderID = oi.OrderID
JOIN Products AS p
ON oi.ProductID = p.ProductID;
或者是使用派生查询或CTE
答案 1 :(得分:3)
在SQL Server中执行此操作的一个技巧是使用apply
:
SELECT o.OrderID, ProductName, OrderDate, ItemPrice, TaxAmount,
DiscountAmount, x.FinalTotal, Quantity, ShipDate,
x.FinalTotal * Quantity AS ItemTotal
FROM Orders o JOIN
OrderItems AS oi
ON o.OrderID = oi.OrderID JOIN
Products AS p
ON oi.ProductID = p.ProductID CROSS APPLY
(SELECT (DiscountAmount - ItemPrice) as FinalTotal) x
答案 2 :(得分:2)
您无法在同一查询中引用派生值
尝试
SELECT o.OrderID
, ProductName
, OrderDate
, ItemPrice
, TaxAmount
, DiscountAmount
,DiscountAmount - ItemPrice AS FinalTotal
, Quantity
, ShipDate
,(DiscountAmount - ItemPrice) * Quantity AS ItemTotal
FROM Orders AS o JOIN OrderItems AS oi
ON o.OrderID = oi.OrderID
JOIN Products AS p
ON oi.ProductID = p.ProductID;
答案 3 :(得分:0)
简单地说,因为您的表中没有名为FinalTotal的列,所以这是一个计算的
请改用以下内容......
SELECT o.OrderID, ProductName, OrderDate, ItemPrice, TaxAmount, DiscountAmount,
DiscountAmount - ItemPrice AS FinalTotal,
Quantity, ShipDate,
(DiscountAmount - ItemPrice) * Quantity AS ItemTotal
FROM Orders AS o JOIN OrderItems AS oi
ON o.OrderID = oi.OrderID
JOIN Products AS p ON oi.ProductID = p.ProductID;