码迷,mamicode.com
首页 > 其他好文 > 详细

将时间点的数据变成时间段的数据

时间:2017-11-04 16:25:26      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:end   else   sele   font   log   sel   case   cas   写法   

已知数据如下:
PC     E     D
工     5      2016-09-01
工     6      2016-09-30
公     5      2016-09-01
公     6      2017-09-30

加入查询开始日期是2016-09-01,结束日期2016-10-07

希望将上面数据变成:
PC        E         S                        N
工         5         2016-09-01      2016-09-30
工         6         2016-09-30      2016-10-07
公         5         2016-09-01      2016-10-07

--创建测试表
create table tmp as 
select  PC, 5 E, to_date(2016-09-01,yyyy-mm-dd) D from dual union all
select  PC, 6 E, to_date(2016-09-30,yyyy-mm-dd) D from dual union all
select  PC, 5 E, to_date(2016-09-01,yyyy-mm-dd) D from dual union all
select  PC, 6 E, to_date(2017-09-30,yyyy-mm-dd) D from dual;

--写法1:
select pc,e,case when to_date(2016-09-01,yyyy-mm-dd) >= d then to_date(2016-09-01,yyyy-mm-dd) else d end s,
       nvl(lead(d,1)over(partition by pc order by d),to_date(2016-10-07,yyyy-mm-dd)) as d from tmp
 where d <= to_date(2016-10-07,yyyy-mm-dd)
 order by pc,s;

--写法2: 
select pc,e,d as s,
       nvl(lead(d,1)over(partition by pc order by d),to_date(2016-10-07,yyyy-mm-dd)) as n 
  from tmp 
 where d <=to_date(2016-10-07,yyyy-mm-dd)
 order by pc,s;

 

将时间点的数据变成时间段的数据

标签:end   else   sele   font   log   sel   case   cas   写法   

原文地址:http://www.cnblogs.com/huangbiquan/p/7783297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!