sql server 2008 - How to return consecutive date ranges frm a set of dates in sql -
i have set of dates table in sql. want return date ranges , need help.
so if had dates this
pk - date 160 - 2013-04-16 12:09:00 160 - 2013-04-17 11:07:00 162 - 2013-04-16 12:10:00 160 - 2013-04-20 12:10:00
i want example
pk - beg - end 160 - 2013-04-16 12:09:00 - 2013-04-17 11:07:00 160 - 2013-04-17 11:07:00 - 2013-04-20 12:10:00 162 - 2013-04-16 12:10:00 - 2013-04-16 12:10:00
can please me.
thank you
i using microsoft sql server management studio 10.0.1600.22
here's example using ms sql server 2008 (though should work 2005+):
with cte ( select rownum = row_number() on (partition pk order date asc), * dates ) select a.pk, a.date [beg], coalesce(b.date, a.date) [end] cte left join cte b on b.pk = a.pk , b.rownum = a.rownum + 1 b.rownum not null or a.rownum = 1
this row numbers each pk, provide joins between table , itself, filtering out rows don't have match unless first row pk.
here's table:
create table dates (pk int, date datetime) insert dates values (160, '2013-04-16 12:09:00'), (160, '2013-04-17 11:07:00'), (162, '2013-04-16 12:10:00'), (160, '2013-04-20 12:10:00')
sql fiddle here (hopefully - been having issues).
Comments
Post a Comment