Using a calculate column in the Where clause

  • How can I use a calculated column in the Where clause of that same Select statement.

    Example:

    Select a.order_number, a.customer, qty_in_stock = stock_calc(<param&gt

    From Orders a

    Where qty_in_stock >10

    This is NOT my actual query but this is the idea I want to implement. Of course I get the error on "qty_in_stock" - "Invalid column name qty_in_stock".

    Is there a work-around on that ?

    Thank you in advance,

    Bob

     

  • Try putting your calculation in the where clause, not the aliased column name

    Select a.order_number, a.customer, qty_in_stock = stock_calc(<param>

    From Orders a

    Where stock_calc(<param&gt > 10

  • Or use a subquery

    Select a.order_number, a.customer, qty_in_stock

    From (

    SELECT order_number, customer, stock_calc(<param> ) AS qty_in_stock 

    FROM Orders) a

    Where qty_in_stock  > 10

    Aliases haven't been processed when the where clause executes, so they cause errors

     

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • Repeat the calculation in the WHERE clause. Yeah, it looks ugly. However, if looks are important to you (and I have to admit, sometimes I get more than a little stuck on looks myself) then you can hide it by filtering through a derived table:

    Select *
    From (
        select  order_number, customer, stock_calc( <param> ) as qty_in_stock
        from orders
    ) as a
    Where qty_in_stock > 10

    I don't usually bother with such simple calculations. Where this comes in handy is when you have a query like:

    select something, otherthing, case when ...
    from sometable
    order by case when...

    Tomm Carr
    --
    Version Normal Form -- http://groups.google.com/group/vrdbms

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply