根據您的樣本數據(我已經放在一個名爲test的表),並假設沒有重疊:
;with Ranges as (
select Code,Start_Date,End_Date,Volume from Test
union all
select r.Code,r.Start_Date,t.End_Date,(r.Volume + t.Volume)
from
Ranges r
inner join
Test t
on
r.Code = t.Code and
DATEDIFF(day,r.End_Date,t.Start_Date) = 1
), ExtendedRanges as (
select Code,MIN(Start_Date) as Start_Date,End_Date,MAX(Volume) as Volume
from Ranges
group by Code,End_Date
)
select Code,Start_Date,MAX(End_Date),MAX(Volume)
from ExtendedRanges
group by Code,Start_Date
說明:
範圍CTE包含原始表中的所有行(由於其中一些可能是相關的),所有的行,我們可以通過形成穰ning在一起(包括原始範圍和我們構造的任何中間範圍 - 我們在這裏做遞歸)。
然後,對於任何特定的End_Date,ExtendedRanges(命名較差)會找到可以達到它的最早的Start_Date。
最後,我們查詢第二個CTE,爲任何特定的Start_Date查找與其關聯的最新End_Date。
這兩個查詢結合在一起,基本上將範圍CTE過濾爲每組重疊日期範圍中的「儘可能最大的Start_Date/End_Date對」。
數據採樣設置:
create table Test (
Code int not null,
Start_Date date not null,
End_Date date not null,
Volume int not null
)
insert into Test(Code, Start_Date, End_Date, Volume)
select 470,'24-Oct-10','30-Oct-10',28 union all
select 470,'17-Oct-10','23-Oct-10',2 union all
select 470,'26-Sep-10','2-Oct-10',2 union all
select 471,'22-Aug-10','29-Aug-10',2 union all
select 471,'15-Aug-10','21-Aug-10',2
go
在您的樣本輸出(現在,它的格式化感謝KM)我不知道爲什麼行 470 26月10 2 2010年10月2 會不會與其他470代碼合併? – 2010-12-03 13:30:15
任何一對行(對於特定的代碼)是否有實際重疊的日期範圍,或者它們會始終是不同的? – 2010-12-03 14:35:14