Reputation: 517
I have the following SQL statements:
Select SUM (amount) from accounts Where acctype = 0;
and
Select SUM (amount) from accounts Where acctype = 1;
I want to find the difference between the amount in two cases in a single SQL statement.
Upvotes: 0
Views: 64
Reputation: 1269563
You can use conditional aggregation:
select sum(case when acctype = 0 then amount
when acctype = 1 then - amount
end) as diff
from accounts;
Upvotes: 1
Reputation: 94884
This is called conditional aggregation:
SELECT
SUM(case when acctype = 0 then amount else 0 end) AS sum0,
SUM(case when acctype = 1 then amount else 0 end) AS sum1,
SUM(case when acctype = 0 then amount else 0 end) -
SUM(case when acctype = 1 then amount else 0 end) AS diff
FROM accounts;
Upvotes: 1