模拟一个数据表如下
有三个字段:年、月、数值。但数据不是连续的。如2014年05月 到2015年04月 缺少 2014年06、08、11、12 以及2015年01、02
-
select '2014' year ,'05' month ,100 val from dual union all
-
select '2014' year ,'07' month ,100 val from dual union all
-
select '2014' year ,'09' month ,100 val from dual union all
-
select '2014' year ,'10' month ,100 val from dual union all
-
select '2015' year ,'03' month ,100 val from dual union all
-
select '2015' year ,'04' month ,100 val from dual
如果要求结果中不能有月份缺少怎么办? 起始年月与终止年月为参数。
下面给出一解决方案,主要是使用dual 表及connect by level 进行生成全月份的一个视图,然后与数据表进行左外连接得到月份连续的结果。
-
with v_date as (
-
select '2014' year ,'05' month ,100 val from dual union all
-
select '2014' year ,'07' month ,100 val from dual union all
-
select '2014' year ,'09' month ,100 val from dual union all
-
select '2014' year ,'10' month ,100 val from dual union all
-
select '2015' year ,'03' month ,100 val from dual union all
-
select '2015' year ,'04' month ,100 val from dual
-
), DATELIST as (
-
select to_char(add_months( to_date('201405','yyyymm') ,level-1 ),'yyyy' ) year,
-
to_char(add_months( to_date('201504','yyyymm') ,level-1 ),'mm' ) month
-
from dual connect by level <= months_between( to_date('201504','yyyymm'),to_date('201405','yyyymm'))+1
-
)
-
-
select t.year,t.month,t1.val from DATELIST t,v_date t1
-
where t.year = t1.year(+) and t.month = t1.month(+)
-
order by t.year,t.month
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30066956/viewspace-1808318/
,如需转载,请注明出处,否则将追究法律责任。