How to reuse a result column in an expression for another result column

前端 未结 9 2283
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-25 10:16

Example:

SELECT
   (SELECT SUM(...) FROM ...) as turnover,
   (SELECT SUM(...) FROM ...) as cost,
   turnover - cost as profit

Sure this is

9条回答
  •  一生所求
    2020-12-25 10:26

    Use a cross apply or outer apply.

    SELECT
      Calc1.turnover,
      Calc2.cost,
      Calc3.profit
    from
       cross apply ((SELECT SUM(...) as turnover FROM ...)) as Calc1
       cross apply ((SELECT SUM(...) as cost FROM ...)) as Calc2
    
       /*
         Note there is no from Clause in Calc 3 below.
         This is how you can "stack" formulas like in excel.
         You can return any number of columns, not just one.
       */
       cross apply (select Calc1.turnover - Calc2.cost as profit) as Calc3
    

提交回复
热议问题