Sql server 在SQL Server中基于日期合并行
我想根据开始日期和结束日期显示数据。代码可以包含不同的日期。如果任何时候intervel继续,那么我需要合并这些行并显示为单行 下面是示例数据Sql server 在SQL Server中基于日期合并行,sql-server,Sql Server,我想根据开始日期和结束日期显示数据。代码可以包含不同的日期。如果任何时候intervel继续,那么我需要合并这些行并显示为单行 下面是示例数据 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
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
代码可以有任意数量的时间间隔。请帮忙。谢谢你如果我理解你的要求,你需要的是:
select code, min(Start_date), max(end_date), sum(volume)
from yourtable
group by code
基于您的样本数据(我将其放入一个名为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
说明:
范围包含原始表中的所有行(因为其中一些行可能是相关的),以及我们可以通过将范围连接在一起形成的所有行(原始范围和我们构造的任何中间范围-我们在这里进行递归)
然后,ExtendedRanges(名称不准确)会为任何特定的结束日期查找可以到达的最早开始日期
最后,我们查询第二个CTE,以查找任何特定开始日期的最新结束日期
这两个查询组合在一起,基本上将范围CTE过滤到每组重叠日期范围中的“最宽的开始日期/结束日期对”
示例数据设置:
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
谢谢你的回复。但您的查询每代码显示一行。从数据上看,2010年10月2日至2010年10月17日之间存在差距。所以代码470Ok应该有两行,但从技术上讲,示例中第一行和第二行之间也有24小时的间隔。如果一行和下一行之间没有时间间隔,那么开始时间和结束时间应该相等,不是吗?是的,完全正确。如果超过24小时,那么diff rows else会将其合并到您的示例输出中(现在已格式化,谢谢KM)。我不确定为什么470 26-Sep-10 2-Oct-10 2行不会与其他470代码合并?任何一对行(对于特定代码)是否会有实际重叠的日期范围,或者它们总是不同的?