Search code examples
sqlselectclause

Reference something in the select clause SQL


I was wondering if you can reference something in the where clause like:

select
sum([some calculation]) as x,
sum([some other calculation]) as y,
x/y as z
from 
[rest of the sql...]

Many Thanks

K


Solution

  • No, you cannot used the alias that was generated on the same level on the SELECT statement.

    Here are the possible ways to accomplish.

    Using the original formula:

    select sum([some calculation]) as x,
           sum([some other calculation]) as y,
           sum([some calculation]) / sum([some other calculation]) as z
    from    tableName
    

    or by using subquery:

    SELECT  x,
            y,
            x/y z
    FROM 
    (
       select sum([some calculation]) as x,
              sum([some other calculation]) as y
       from   tableName
    ) s