ITPub博客

首页 > 数据库 > Oracle > 使用dual 虚表,构造连续数据

使用dual 虚表,构造连续数据

原创 Oracle 作者:self_control 时间:2015-09-24 16:17:27 0 删除 编辑
模拟一个数据表如下
有三个字段:年、月、数值。但数据不是连续的。如2014年05月 到2015年04月 缺少 2014年06、08、11、12 以及2015年01、02

点击(此处)折叠或打开

  1. select '2014' year ,'05' month ,100 val from dual union all
  2. select '2014' year ,'07' month ,100 val from dual union all
  3. select '2014' year ,'09' month ,100 val from dual union all
  4. select '2014' year ,'10' month ,100 val from dual union all
  5. select '2015' year ,'03' month ,100 val from dual union all
  6. select '2015' year ,'04' month ,100 val from dual
如果要求结果中不能有月份缺少怎么办? 起始年月与终止年月为参数。
下面给出一解决方案,主要是使用dual 表及connect by level 进行生成全月份的一个视图,然后与数据表进行左外连接得到月份连续的结果。

点击(此处)折叠或打开

  1. with v_date as (
  2.      select '2014' year ,'05' month ,100 val from dual union all
  3.      select '2014' year ,'07' month ,100 val from dual union all
  4.      select '2014' year ,'09' month ,100 val from dual union all
  5.      select '2014' year ,'10' month ,100 val from dual union all
  6.      select '2015' year ,'03' month ,100 val from dual union all
  7.      select '2015' year ,'04' month ,100 val from dual
  8. ), DATELIST as (
  9.     select to_char(add_months( to_date('201405','yyyymm') ,level-1 ),'yyyy' ) year,
  10.     to_char(add_months( to_date('201504','yyyymm') ,level-1 ),'mm' ) month
  11.     from dual connect by level <= months_between( to_date('201504','yyyymm'),to_date('201405','yyyymm'))+1
  12. )

  13. select t.year,t.month,t1.val from DATELIST t,v_date t1
  14. where t.year = t1.year(+) and t.month = t1.month(+)
  15. order by t.year,t.month

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30066956/viewspace-1808318/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-12-16

  • 博文量
    49
  • 访问量
    406897