Memory Tee
Memory Tee

Reputation: 1

Getting the difference of two sums from the same table

I need to get the difference of a query result from the same table.

Ex: myTable

id    code     status     amount
1       A       active      250
2       A       active      200
3       B       active      300
4       B       active      100
5       A       active      100
6       C       active      120
7       C       active      200

I want to get the total or sum of amount for each code (add if active, subtract if inactive status) so that i will have a result like this:

code   total amount
A         150
B         400
C          80

i have tried a lot already, one of them is this:

SELECT code, amount1-amount2
FROM (
    SELECT code, SUM(amount) AS amount1
    FROM mytable
    WHERE status='active'
    GROUP BY code
    UNION ALL
    SELECT code, SUM(amount) AS amount2
    FROM mytable
    WHERE status='inactive'
    GROUP BY code
) as T1
GROUP BY code

Upvotes: 0

Views: 310

Answers (2)

jpw
jpw

Reputation: 44891

The simplest solution would be to use a case expression inside the sum function:

SELECT 
    code, 
    sum(case when status='active' then amount else amount * -1 end) as total_amount
FROM mytable
GROUP BY code

If there can be other statuses besides active/inactive you have to be more explicit:

sum(
   case 
      when status = 'active'   then amount 
      when status = 'inactive' then amount * -1
   end
) AS total

Upvotes: 1

Carlos Prieto
Carlos Prieto

Reputation: 21

WITH A AS
(SELECT
   code,
   CASE WHEN status='active' THEN amount ELSE -amount END AS signed_amount
FROM myTable)

SELECT code, sum(signed_amount) FROM A GROUP BY code;

Upvotes: 0

Related Questions