我试图从一组提供给定月份和年份的分钟数的数据中获得 12 个月的滚动总数。在很多情况下,我一个月都没有记录。有没有办法以零 (0) 的值显示缺失的月份,然后将其卷起或不显示它们,但让查询将其确认为 12 个月范围的一部分。下面的查询是我试图使用的,但它只是抓取了以前的记录,并没有考虑到丢失的月份。下面的查询似乎与一些总数并没有什么不同。任何帮助将不胜感激。
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
这是创建测试表和数据的sql。
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;