2017-01-10 157 views
0

我在SQL Server中Reports表这样的合并在SQL Server中记录:的开始和结束时间

Report Table

我需要与同一CallNumbertype = Unanswered和区别StartDate一个记录合并在此表中的记录而EndDate另一个小于1。 例如差异化经营的,请看到这一点:

result table

结果表是这样的:

Result

我执行此查询获取记录应合并,但我不知道知道如何合并这个记录。

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 

如果某人能够解释返回结果表的查询,那将会非常有帮助。

+0

您需要查询还是需要永久删除该数据? –

+0

@GiorgiNakeuri我需要查询返回结果表。 –

+0

我不确定你的意思是什么,“StartDate一条记录,EndDate另一条记录少于一条”。我认为这段时间必须是连续的,一段时间结束,下一段开始一秒钟(如前两个例子),但在第三个例子中,记录之间有5秒的间隔。那么这个短语意味着什么? –

回答

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;