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

Wernight picture Wernight · Nov 19, 2010 · Viewed 85.5k times · Source

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?

Answer

Denis de Bernardy picture Denis de Bernardy · Jul 21, 2011

Like so:

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