Oracle SQL Calculating Variance

时间:2017-06-04 23:44:32

标签: sql oracle11g

Lets say I have a table like so:

ID         TYPE          MONTH       AMOUNT         
--         ----          ----          ---          

abc        Forecast       1           150          
def        Forecast       1           225          
abc        Budget         1           140          
def        Budget         1           250         
abc        Forecast       2           190          
abc        Budget         2           450  

What I want to do is insert a record for each ID that is the difference between the Forecast and the Budget for each month. So result would look like this:

ID         TYPE          MONTH       AMOUNT         
--         ----          ----          ---          

abc        Forecast       1           150          
def        Forecast       1           225          
abc        Budget         1           140          
def        Budget         1           250         
abc        Forecast       2           190          
abc        Budget         2           450 
abc        Variance       1           10
abc        Variance       2          -260
def        Variance       1          -25   

could someone please provide the SQL for this. Thank you!

1 个答案:

答案 0 :(得分:2)

You can use conditional aggregation to get the difference and insert the variance rows. (This assumes each id,month combination has Forecast and Budget rows. If not, add else 0 in each max)

insert into tbl(id,type,month,amount)
select id,'Variance',month,
max(case when type='Forecast' then amount end) - max(case when type='Budget' then amount end) 
from tbl
group by id,month