Jayaram
Jayaram

Reputation: 6606

postgres Finding the difference between numbers of the same column

I have a table like the below

| date       | key | value |   |
|------------|-----|-------|---|
| 01-01-2009 | a   | 25    |   |
| 01-01-2009  | b   | 25    |   |
| 01-01-2009  | c   | 10    |   |

I'm trying to come up with a query which would allow me to do (a+b)-c for each day - but my join is doing this (a+b+c)-c

with total as (
select
    sum(value),
    date
from
    A
where
    key in ('a',
    'b')
group by
    date ) 
select
    sum(total.sum) as a, sum(A.value) as b,
    sum(total.sum) - sum(A.value) as value,
        A.date
    from
        A
    join total on
        total.date = A.date
    where
        A.key = 'c'
    group by
        A.date

This is giving me a value of 50 (it should be 40) - my C values are getting calcualted as part of the total table during the join

What am i doing wrong?

Upvotes: 1

Views: 1321

Answers (2)

The Impaler
The Impaler

Reputation: 48770

You can join three table expressions, as in:

select
  a.date,
  (a.value + b.value) - c.value
from (select * from A where key = 'a') a
join (select * from A where key = 'b') b on b.date = a.date
join (select * from A where key = 'c') c on c.date = a.date

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1269503

How about simply doing conditional aggregation?

select date,
       sum(case when key in ('a', 'b') then value 
                when key in ('c') then - value
           end) as daily_calc
from a
group by date;

A join doesn't seem very helpful for this calculation.

Upvotes: 3

Related Questions