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?
Use the results of a query as a field in another query. You can use a subquery as a field alias. Use a subquery as a field alias when you want to use the subquery results as a field in your main query. Note: A subquery that you use as a field alias cannot return more than one field.
Like so:
SELECT turnover, cost, turnover - cost as profit from ( (SELECT SUM(...) FROM ...) as turnover, (SELECT SUM(...) FROM ...) as cost ) as partial_sums
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With