create table t2 (id varchar(10),price int ,rq date);
insert into t2 values('001',23,'2013-07-15');
insert into t2 values('001',38,'2013-08-03');
insert into t2 values('001',31,'2013-08-10');
insert into t2 values('002',23,'2013-07-13');
insert into t2 values('002',38,'2013-07-23');
insert into t2 values('002',31,'2013-08-10');
select * from t2 order by id,rq
select id,price,rq as 开始日期,lag(rq-1,-1,'2099-12-31'::date) over(partition by id order by id,rq) as 结束日期
from t2 order by id,rq
可以得到以下结果:
"001";23;"2013-07-15";"2013-08-02"
"001";38;"2013-08-03";"2013-08-09"
"001";31;"2013-08-10";"2099-12-31"
"002";23;"2013-07-13";"2013-07-22"
"002";38;"2013-07-23";"2013-08-09"
"002";31;"2013-08-10";"2099-12-31"
转载于:https://blog.51cto.com/lvbuwei/1266708