Question

I have a simple table in ORACLE that looks like the following

name         size    date
-------------------------
feature1     207      01/01/2013
feature2     203      01/01/2013
feature3     205      01/01/2013

feature1     209      01/01/2014
feature2     139      01/01/2014
feature3     300      01/01/2014

I need to be able to determine the difference (either + or -) between 2013 and 2014 for each individual record.

The output I that I want would look like this

name         diff
-------------------
feature1     2   
feature2     -64  
feature3     95

Is there an easy way to achieve this result without having to create a cursor and iterate through each record individually?

Was it helpful?

Solution 2

Another way, assuming you only want those specific years and have data for both years for each name:

select name_col,
  min(case when extract(year from date_col) = 2014 then size_col end)
    - min(case when extract(year from date_col) = 2013 then size_col end)
from <your table>
group by name_col
order by name_col;

If you don't have data for both years you could wrap each min in nvl(min(...), 0).

SQL Fiddle. Gordon's is a more general approach though...

OTHER TIPS

You can get the previous value using the analytic function lag():

select name, (size - prevsize) as diff
from (select t.*, lag(size) over (partition by name order by date) as prevsize
      from t
     ) t
where prevsize is not null;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top