0

Convert list of dates in a date range in SQL Server

For ex:

enter image description here

asked Feb 15, 2018 at 7:13
1
  • How do you obtain those intervals? I see 7 records on the left and only 6 values on the right. Commented Feb 15, 2018 at 9:39

1 Answer 1

3

It's classic "islands" problem.

Here is "classic" solution:

declare @t table (dt date);
insert into @t(dt) values 
 ('20180202'), 
 ('20180203'), 
 ('20180204'), 
 ('20180205'), 
 ('20180209'), 
 ('20180212'), 
 ('20180213');
with c as 
( 
 select dt, dateadd(day, -1 * dense_rank() over(order by dt), dt) as grp 
 from @t 
) 
select min(dt) as start_range, max(dt) as end_range 
from c 
group by grp;
answered Feb 15, 2018 at 7:42
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.