Use value of a column for another column (SQL Server)?

后端 未结 4 1664
死守一世寂寞
死守一世寂寞 2021-02-19 00:02

lets say I have a huge select on a certain table. One value for a column is calculated with complex logc and its called ColumnA. Now, for another column, I need the val

4条回答
  •  长发绾君心
    2021-02-19 00:27

    If you want to reference a value that's computed in the SELECT clause, you need to move the existing query into a sub-SELECT:

    SELECT
        /* Other columns */,
        ColumnA,
        ColumnA + 10 as ColumnB
    FROM
    (select table.id, table.number, complex stuff [ColumnA].. from table ...
    ) t
    

    You have to introduce an alias for this table (in the above, t, after the closing bracket) even if you're not going to use it.

    (Equivalently - assuming you're using SQL Server 2005 or later - you can move your existing query into a CTE):

    ;WITH PartialResults as (
         select table.id, table.number, complex stuff [ColumnA].. from table ...
    )
    SELECT /* other columns */, ColumnA, ColumnA+10 as ColumnB from PartialResults
    

    CTEs tend to look cleaner if you've got multiple levels of partial computations being done, I.e. if you've now got a calculation that depends on ColumnB to include in your query.

提交回复
热议问题