按开始和结束时间合并SQL Server中的记录

时间:2017-01-10 09:50:35

标签: sql-server tsql

我在SQL Server中有Reports表,如下所示:

Report Table

我需要将此表中的记录与相同的CallNumbertype = Unanswered以及差异StartDate一条记录合并,而EndDate另一条记录小于一条记录。 例如差异操作请参见:

result table

结果表是这样的:

Result

我执行此查询以获取应该合并的get记录,但我不知道如何合并此记录。

select t1.CallNumber,t1.id,t1.EndDate,t2.Id,t2.StartDate 
from Reports as t1
left join Reports as t2 on t1.CallNumber = t2.CallNumber and t1.type=t2.type
where 
    t1.EndDate < t2.StartDate
    and DATEDIFF(MINUTE,t1.EndDate,t2.StartDate) < 1
    and t1.type = 'Unanswered'
group by t1.CallNumber,t1.id,t1.EndDate,t2.Id,t2.StartDate

如果有人可以解释返回结果表的查询解决方案,那将非常有用。

1 个答案:

答案 0 :(得分:1)

这对你有什么用?

declare @t table(ID int
                ,Number int
                ,StartDate datetime
                ,EndDate datetime
                ,Type nvarchar(50)
                );
insert into @t values
 (1 ,2024,'20160102 16:40:00','20160102 16:40:15','Unanswered')
,(2 ,2024,'20160102 16:40:16','20160102 16:40:32','Unanswered')
,(3 ,2060,'20160102 16:40:33','20160102 16:40:48','Answered')
,(4 ,2060,'20160102 16:42:00','20160102 16:42:10','Answered')
,(11,2061,'20160102 16:50:00','20160102 16:50:10','Unanswered')
,(12,2062,'20160102 16:50:14','20160102 16:50:24','Unanswered')
,(13,2061,'20160102 16:50:30','20160102 16:50:44','Unanswered');

select *
from @t t1
    left join @t t2
        on(t1.ID <> t2.ID
            and t1.StartDate > t2.StartDate
            and datediff(s, t2.EndDate, t1.StartDate) < 60  -- DATEDIFF only records boundaries crossed, so 14:34:59 to 14:35:00 would count as 1 minute despite actually being just 1 second.
            and t1.Type = t2.Type
            and t1.Type = 'Unanswered'
            )
where t2.ID is null;