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?
Advertisement
Answer
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.