Sql 无效的列名';最终总额';
这是我的代码,它一直在说无效的列名“FinalTotal”。我做错了什么?不能在同一查询中引用派生值 试一试Sql 无效的列名';最终总额';,sql,sql-server,Sql,Sql Server,这是我的代码,它一直在说无效的列名“FinalTotal”。我做错了什么?不能在同一查询中引用派生值 试一试 不能在同一查询级别上使用这样的列别名 在计算ItemTotal时使用FinalToal的完整表达式 SELECT o.OrderID , ProductName , OrderDate , ItemPrice , TaxAmount , DiscountAmount ,DiscountAmount - ItemPrice AS FinalTotal , Quantity , ShipDa
不能在同一查询级别上使用这样的列别名 在计算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,因为表中没有名为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;
在SQL Server中执行此操作的一个技巧是使用
apply
:
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;
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;
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