Missy Missy - 2 months ago 4x
SQL Question

Do Math on Two Scalar Queries in SQL

I'm trying to get the difference of two sum() queries. This is the idea of the code I'm trying to figure out.

(SELECT sum(depamt) FROM Daily1) - (SELECT sum(depamt) FROM Daily2)

I tried declaring variables but I couldn't get the result of the select into the variables. Is there any way of doing this?


Just put a SELECT in front:

SELECT (SELECT sum(depamt) FROM Daily1) - (SELECT sum(depamt) FROM Daily2);

I prefer putting subqueries in the FROM clause:

SELECT sum1 - sum2
FROM (SELECT sum(depamt) as sum1 FROM Daily1) x CROSS JOIN
     (SELECT sum(depamt) as sum2 FROM Daily2) y;

This allows you to choose each value individually, if you like.