SQL Server Reference a Calculated Column

前端 未结 6 1074
傲寒
傲寒 2020-12-30 21:23

I have a select statement with calculated columns and I would like to use the value of one calculated column in another. Is this possible? Here is a contrived example to s

6条回答
  •  星月不相逢
    2020-12-30 21:45

    Two ways I can think of to do that. First understand that the calval1 column does not exist as far as SQL Server is concerned until the statement has run, therefore it cannot be directly used as showning your example. So you can put the calculation in there twice, once for calval1 and once as substitution for calcval1 in the calval2 calculation. The other way is to make a derived table with calval1 in it and then calculate calval2 outside the derived table something like:

    select calcval1*.25 as calval2, calval1, field1, field2
    from (select casestament as cavlval1, field1, field2 from my table) a
    

    You'll need to test both for performance.

提交回复
热议问题