Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid column name 'FinalTotal'

Tags:

sql

sql-server

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;

Here is my code, it keeps saying invalid column name 'FinalTotal'. What am I doing wrong here?

like image 608
LindaS Avatar asked Mar 24 '26 15:03

LindaS


2 Answers

you can't use a column alias on the same query level like that.

use the full expression of FinalToal in the calculation of ItemTotal

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;

alternatively is to use derived query or CTE

like image 70
Squirrel Avatar answered Mar 26 '26 04:03

Squirrel


One trick for doing this in SQL Server is to use 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
like image 31
Gordon Linoff Avatar answered Mar 26 '26 06:03

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!