declare @T table ( [Date] datetime, Code char(1) ) inse...

0

Please login or register to vote for this query.

(click on this box to dismiss)

Stack Overflow

Q&A for programmers

-- Enter Query Title
-- Enter Query Description

declare @T table
(
  [Date] datetime,
  Code char(1)
)

insert into @T values
('1/1/2011','A'),  
('1/2/2011','A'),  
('1/3/2011','A'),  
('1/1/2011','B'),  
('1/2/2011','B'),
('2/1/2011','A'),
('2/2/2011','A'),
('2/27/2011','A'),
('2/28/2011','A'),
('3/1/2011','A'),
('3/2/2011','A'),
('3/3/2011','A'),
('3/4/2011','A')

;with C as
(
  select *,
         datediff(day, 0, [Date]) - row_number() over(partition by Code 
                                                      order by [Date]) as rn
  from @T
)  
select min([Date]) as StartDate,
       max([Date]) as EndDate,
       Code
from C
group by Code, rn

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results
:records returned in :time ms:cached