Getting the difference of two sums from the same table

时间:2015-09-01 22:33:18

标签: sql postgresql postgresql-9.4

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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;