Reputation: 137
I'm using Oracle.
Having a table as:
Year Type Value
2011 1 500
2011 2 550
2011 3 600
...
...
2012 1 600
2012 2 750
2012 3 930
I need to subtract all the values from different types, grouped by year. The operation would be:
For 2011 -> 1-2-3 (500-550-600)
For 2012 -> 1-2-3 (600-750-930)
For ...
The result should be:
Year Value
2011 -650
2012 -1080
... ...
I'm just not managing to get this query working..
Upvotes: 0
Views: 8547
Reputation: 44796
You mean GROUP BY, CASE to decide sign +for type 1, - for others:
select "year",
SUM(case when type = 1 then value else -value end)
from yourtable
group by "year"
Upvotes: 0
Reputation: 1270463
Use conditional aggregation:
select sum(case when type = 1 then value else - value end) as value
from table t
group by year;
Upvotes: 8