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

前端 未结 9 2317
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-25 10:23

    this is pretty old but i ran into this problem and saw this post but didnt manage to solve my problem using the given answers so i eventually arrived at this solution :

    if your query is :

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

    you can turn it into a subquery and then use the fields such as :

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

    i'm not entirely sure if this is a bad way of doing things but performance wise it seems okay for me querying over 224,000 records took 1.5 sec not sure if its later on turned into 2x of the same sub query by DB.

提交回复
热议问题