Search code examples
sqlsql-servercolumn-alias

Msg 207, Level 16, State 1, Line 1 Invalid column name 'ItemTotal'


I wrote this code. It works fine without my WHERE Statement. I keep getting an error

Msg 207, Level 16, State 1, Line 1 Invalid column name 'ItemTotal'.

I don't know what I did wrong!

SELECT    
    ItemID, 
    ItemPrice,    
    ItemPrice * quantity AS PriceTotal,
    DiscountAmount * quantity AS DiscountTotal,
    ((ItemPrice - DiscountAmount) * quantity) AS ItemTotal
FROM                                                                                                                                                               
    OrderItems
WHERE ItemTotal > 500;

Solution

  • No database platform was given, but based on the query: 'ItemTotal' is not a column you can use, as it's an alias. You need to filter on the actual data

    SELECT    
        ItemID, 
        ItemPrice,    
        ItemPrice * quantity AS PriceTotal,
        DiscountAmount * quantity AS DiscountTotal,
        ((ItemPrice - DiscountAmount) * quantity) AS ItemTotal
    FROM                                                                                                                                                               
        OrderItems
    WHERE ((ItemPrice - DiscountAmount) * quantity) > 500;