2010-12-03 53 views
4

我想根據開始日期和結束日期顯示數據。一個代碼可以包含不同的日期。如果有時間有限區間被繼續然後我需要合併的行而顯示爲單行 這裏是樣本數據根據SQL Server中的日期合併行

Code Start_Date End_Date  Volume 
470 24-Oct-10 30-Oct-10 28 
470 17-Oct-10 23-Oct-10  2 
470 26-Sep-10  2-Oct-10  2 
471 22-Aug-10 29-Aug-10  2 
471 15-Aug-10 21-Aug-10  2 

輸出的結果我想是

Code Start_Date End_Date  Volume 
470 17-Oct-10 30-Oct-10 30 
470 26-Sep-10  2-Oct-10  2 
471 15-Aug-10 29-Aug-10  4 

一個代碼可以有任何沒有。時間間隔。請幫助。謝謝

+0

在您的樣本輸出(現在,它的格式化感謝KM)我不知道爲什麼行 470 26月10 2 2010年10月2 會不會與其他470代碼合併? – 2010-12-03 13:30:15

+0

任何一對行(對於特定的代碼)是否有實際重疊的日期範圍,或者它們會始終是不同的? – 2010-12-03 14:35:14

回答

2

根據您的樣本數據(我已經放在一個名爲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 
3

,如果我明白你的要求,你正在尋找的東西,如:

select code, min(Start_date), max(end_date), sum(volume) 
from yourtable 
group by code 
+0

感謝您的回覆。但是您的查詢每個代碼顯示單行。在數據方面,2010年10月2日至2010年10月17日之間存在差距。所以我們應該得到2行代碼470 – Bhushan 2010-12-03 13:27:09