开发者

Concatenate date ranges in SQL (T/SQL preferred)

I need to concatenate rows with a date and a code into a date range

Table with two columns that are a composite primary key (date and a code )

Date        Code  
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

Needs to be converted to

Start Date    End Date    Code
开发者_Python百科1/1/2011      1/3/2011    A
2/1/2011      2/2/2011    A
1/1/2011      1/2/2011    B
2/27/2011     3/4/2011    A

Is there any other way or is a cursor loop the only way?


declare @T table
(
  [Date] date,
  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'), 
('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


sql server 2000 has it limitations. Rewrote the solution to make it more readable.

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'),  
('3/1/2011','A'), 
('3/2/2011','A'), 
('3/3/2011','A'), 
('3/4/2011','A') 

select a.code, a.date, min(b.date)
from
(
    select *
    from @t t 
    where not exists (select 1 from @t where t.code = code and t.date -1 = date)
) a
join 
(
    select *
    from @t t 
    where not exists (select 1 from @t where t.code = code and t.date  = date -1)
) b
on a.code = b.code and a.date <= b.date
group by a.code, a.date


Using a DatePart function for month will get you the "groups" you want

SELECT Min(Date) as StartDate, Max(Date) as EndDate, Code 
FROM ThisTable Group By DatePart(m, Date), Code
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜