title: SQL Conditional aggregation
body: <p>I'm using Oracle.</p>
  
  <p>Having a table as:</p>
  
  <pre><code>Year   Type   Value
  2011   1       500
  2011   2       550
  2011   3       600
  ...
  ...
  2012   1       600
  2012   2       750
  2012   3       930
  </code></pre>
  
  <p>I needed to subtract all the values from different types, grouped by year.
  The operation would be:</p>
  
  <p>For 2011 -> 1-2-3 (500-550-600)</p>
  
  <p>For 2012 -> 1-2-3 (600-750-930)</p>
  
  <p>For ...</p>
  
  <p>The result shoud be:</p>
  
  <pre><code>Year   Value
  2011   -650  
  2012   -1080 
  ...    ...  
  </code></pre>
  
  <p>I couldn't do it but here on stack overflow this query was suggested, and it worked:</p>
  
  <pre><code>select sum(case when type = 1 then value else - value end) as value
  from table t
  group by year;
  </code></pre>
  
  <p>But now, i have another situation. I need to do the same thing but not 1-2-3-4-5-... But 1+2-3-4-5-6....</p>
  
  <p>To to this i tried this both queries, with no sucess:</p>
  
  <pre><code>select sum(case when type = 1 then value when type = 2 then value else - value end) as value
  from table t
  group by year;
  </code></pre>
  
  <p>This resulted in the second value has its value doubled. </p>
  
  <pre><code>select sum(case when type = 1 then value else - value end)+case when type =     2 then value as value
  from table t
  group by year; 
  </code></pre>
  
  <p>This resulted in a correct type 2 value, but,as this type 2 only accurs in some years, the other years show up as null. So, the final calculation is correct for type 2 (the years it is in) but for every other year, for each type 2 does not exist, it returns null.</p>
  
  <p>I'm just not managing to get this query working..
  Any idea would be greatly appreciated!
  Thanks</p>