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

前端 未结 9 2285
爱一瞬间的悲伤
爱一瞬间的悲伤 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:34

    Perhaps the sql "with" clause could help, as presented here http://orafaq.com/node/1879 (other databases such as Postgres do it as well, not just oracle).

    0 讨论(0)
  • 2020-12-25 10:34
    SELECT turnover, cost, turnover - cost
    FROM
    (
    SELECT
    (SELECT ...) as turnover,
    (SELECT ...) as cost
    ) as Temp
    
    0 讨论(0)
  • 2020-12-25 10:38

    Actually I did a lot of work on this, and hit many brick walls, but finally figured out an answer - more of a hack - but it worked very well and reduced the read overhead of my queries by 90%....

    So rather than duplicating the correlated query many times to retrieve multiple columns from the subquery, I just used concat all the values I want to return into a comma separated varchar, and then unroll them again in the application...

    So instead of

    select a,b,
    (select x from bigcorrelatedsubquery) as x,
    (select y from bigcorrelatedsubquery) as y,
    (select z from bigcorrelatedsubquery) as z
    from outertable
    

    I now do

    select a,b,
    (select convert(varchar,x)+','+convert(varchar,x)+','+convert(varchar,x)+',' 
    from bigcorrelatedsubquery) from bigcorrelatedquery) as xyz
    from outertable
    group by country
    

    I now have all three correlated 'scalar' values I needed but only had to execute the correlated subquery once instead of three times.

    0 讨论(0)
提交回复
热议问题