ITPub博客

首页 > 数据库 > Oracle > 巧用rownum查询连续季度 VelHong

巧用rownum查询连续季度 VelHong

Oracle 作者:wznjc 时间:2013-12-28 10:47:27 0 删除 编辑
巧用rownum查询连续季度
分类: Oracle2011-11-09 11:21 478人阅读 评论(0) 收藏 举报


   下面可以说是这类查询的一个模版SQL,如果大家在工作中碰到类似的问题,可以借助该SQL去解决,希望能帮助到大家。

 

  1. select count(1)  
  2.   from (select t.*, rownum rnum  
  3.           from (select t.quarter  
  4.                   from 表名 t  
  5.                  where t.quarter <= '201103'  
  6.                  group by t.quarter  
  7.                  order by t.quarter desc) t) t  
  8.  where (to_number(substr('201103', 0, 4)) -  
  9.        to_number(substr(t.quarter, 0, 4))) * 4 +  
  10.        ((to_number(substr('201103', 5, 6)) + 1 -  
  11.        to_number(substr(t.quarter, 5, 6)))) = t.rnum  
  12.    and t.rnum = rownum  

说明:季度存放格式201001,表示2010年1季度,以此类推。

另也可以使用row_number() over(order by t.quarter desc)减少一层select,代码如下:

  1. select count(1)  
  2.   from (select row_number() over(order by t.quarter desc) rnum,  
  3.                t.quarter  
  4.           from 表名 t  
  5.          where t.quarter <= '201103'  
  6.          group by t.quarter  
  7.          order by t.quarter desc) t  
  8.  where (to_number(substr('201103', 0, 4)) -  
  9.        to_number(substr(t.quarter, 0, 4))) * 4 +  
  10.        ((to_number(substr('201103', 5, 6)) + 1 -  
  11.        to_number(substr(t.quarter, 5, 6)))) = t.rnum  
  12.    and t.rnum = rownum;  


至于rownum和row_number() 在使用上的区别,本人建议还是直接使用原生态的rownum,因为这样子的效率是最高的 
<!-- 正文结束 -->

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

上一篇: 没有了~
下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2011-09-11