I am trying to get a rolling 12 month total from a set of data that provides the minutes for a given month and year. In many cases, I will not have a a record for a month. Is there a way to display the missing months with a zero (0) for the value and then roll it up or not display them but have the query acknowledge this as part of the 12 month range. The below query is what I was trying to use but it just grabs the prior records and does not take into account missing months. The query below does not seems to be off a little with some of the totals. Any assistance would be greatly appreciated.
Select year
, month
, SUM(NVL(minutes, 0)) OVER (order by year,month rows between 11 preceding and current row) as total_minutes
from
(
Select *
from test_table
Order by year, month
)
Order by year desc , month desc
Here is the sql to create the test table and data.
drop table test_table;
create table test_table (
month number(2),
year number(4),
minutes number(4,2)
);
insert into test_table values ( 1, 2012, 3 );
insert into test_table values ( 2, 2012, 3 );
insert into test_table values ( 3, 2012, 3 );
insert into test_table values ( 4, 2012, 4 );
insert into test_table values ( 5, 2012, 5 );
insert into test_table values ( 7, 2012, 5 );
insert into test_table values ( 8, 2012, 5 );
insert into test_table values ( 9, 2012, 5 );
insert into test_table values (10, 2012, 4 );
insert into test_table values (11, 2012, 3 );
insert into test_table values (12, 2012, 3 );
insert into test_table values ( 1, 2011, 3 );
insert into test_table values ( 2, 2011, 3 );
insert into test_table values ( 5, 2011, 5 );
insert into test_table values ( 6, 2011, 5 );
insert into test_table values ( 7, 2011, 5 );
insert into test_table values ( 8, 2011, 5 );
insert into test_table values ( 9, 2011, 5 );
insert into test_table values (10, 2011, 4 );
insert into test_table values (11, 2011, 3 );
insert into test_table values (12, 2011, 3 );
insert into test_table values ( 1, 2010, 3 );
insert into test_table values ( 2, 2010, 3 );
insert into test_table values ( 3, 2010, 3 );
insert into test_table values ( 4, 2010, 4 );
insert into test_table values ( 5, 2010, 4 );
insert into test_table values ( 6, 2010, 5 );
insert into test_table values ( 7, 2010, 5 );
insert into test_table values (10, 2010, 4 );
insert into test_table values (11, 2010, 4 );
insert into test_table values (12, 2010, 3 );
COMMIT;
I did use the outer join but that didn’t give me the rolling 12 month range that I needed. I had to use the Windowing Clause to get the range and numbers to come out right.