63

Example:

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

Sure this is invalid (at least in Postgres) but how to achieve the same in a query without rewriting the sub-query twice?

6
  • Depends on details, such as columns & tables involved. Commented Nov 18, 2010 at 23:13
  • @OMG Ponis: Like? Isn't there a general way for such? Commented Nov 18, 2010 at 23:20
  • I agree with @OMG. That said, if you can write one subquery that returns both turnover and cost as columns, the query wrapped around that subquery can perform turnover - cost. For more details, we'll need some details about your schema. Commented Nov 18, 2010 at 23:21
  • 2
    Also consider using "common table expressions" aka CTE. See stackoverflow.com/questions/2686919/… and postgresql.org/docs/8.4/static/queries-with.html Commented Dec 11, 2012 at 9:12
  • Edited title: this question doesn't focus on reusing subqueries (tables) but rather single columns, unlike stackoverflow.com/q/2686919/648265 . Commented Nov 24, 2015 at 10:42

9 Answers 9

51

Like so:

SELECT
   turnover,
   cost,
   turnover - cost as profit
from (
   (SELECT SUM(...) FROM ...) as turnover,
   (SELECT SUM(...) FROM ...) as cost
   ) as partial_sums
Sign up to request clarification or add additional context in comments.

9 Comments

Usually when you do select from table1, table2 you get the CROSS JOIN of the two tables. What does select from (table1, table2) as bla (as you have here) do with the two tables?
@CharlBotha: it's not select from (foo, bar). It's [select] (select sum from foo), (select sum from bar) [from nothing].
In your example above, you have ... from ((select ...) as turnover, (select ...) as cost) as partial_sums -- I'm still wondering how exactly the turnover and cost sub-selects are combined?
@CharlBotha: they're two scalars, in very much the same way as you'd go select 1 as foo, 2 as bar.
What about if the subselect uses a common FROM as well :S
|
15

You could reuse the query like this:

WITH 
  TURNOVER AS (
    SELECT SUM(...) FROM ...)
  ),
  COST AS(
    SELECT SUM(...) FROM ...
  )

SELECT *
FROM(
 SELECT
   TURNOVER.sum as SUM_TURNOVER
 FROM
 TURNOVER,COST
 WHERE ....
) AS a

This is equivalent to :

SELECT *
FROM(
 SELECT
   TURNOVER.sum as SUM_TURNOVER
 FROM
 (
   SELECT SUM(...) FROM ...)
 )AS TURNOVER,
 (
   SELECT SUM(...) FROM ...
 )AS COST
 WHERE ....
) AS a

There is a point to note here. The first method is more readable and reusable, but the second method might be faster, because the DB might choose a better plan for it.

Comments

7

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).

1 Comment

This feature is called "common table expressions" aka CTE. See stackoverflow.com/questions/2686919/…
5
SELECT turnover, cost, turnover - cost
FROM
(
SELECT
(SELECT ...) as turnover,
(SELECT ...) as cost
) as Temp

3 Comments

if turnover and cost are table aliases, you definitely can't do this: turnover - cost as profit
Invalid: ERROR: subquery in FROM must have an alias HINT: For example, FROM (SELECT ...) [AS] foo.
In my query Temp is the alias for the subquery in FROM
4

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.

1 Comment

What you should have done is JOIN the bigcorrelatedsubquery with outertable once, instead of repeating it multiple times or resorting to the concat hack. Even in the worst case you could have factored that subquery as a CTE to avoid repeating it.
3

I think the following will work:

SELECT turnover, cost, turnover-cost as profit FROM
   (SELECT 1 AS FAKE_KEY, SUM(a_field) AS TURNOVER FROM some_table) a
INNER JOIN
   (SELECT 1 AS FAKE_KEY, SUM(a_nother_field) AS COST FROM some_other_table) b
USING (FAKE_KEY);

Not tested on animals - you'll be first! :-)

Share and enjoy.

1 Comment

You don't need INNER JOIN with a fake key. Just use a CROSS JOIN, or list the derived tables in a table list: FROM (SELECT ..), (SELECT ..)
0

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

1 Comment

That's T-SQL syntax, only supported by SQL Server and Oracle. In PostgreSQL, this approach would require standard SQL LATERAL derived tables.
0

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.

Comments

-1

You can use user defined variables like this

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

http://dev.mysql.com/doc/refman/5.7/en/user-variables.html

1 Comment

Perhaps this helps in MySQL but for Postgres?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.