查找SQL中具有重叠的警报类型的时间段

时间:2015-04-17 15:20:55

标签: sql sql-server

我有一个像这样的数据集(DATA) -

Store   Start                End                    Type   
XXXX    02-03-2015 10:04:00  02-03-2015 10:08:00    1  
XXXX    02-03-2015 10:06:00  02-03-2015 10:10:00    2  
XXXX    02-03-2015 10:09:30  02-03-2015 10:12:00    1  
YYYY    03-03-2015 20:04:00  03-03-2015 20:12:00    1  
YYYY    03-03-2015 20:06:00  03-03-2015 20:10:00    2  
YYYY    03-03-2015 20:09:00  03-03-2015 20:16:00    1  
YYYY    03-03-2015 20:15:00  03-03-2015 20:18:00    2  
YYYY    03-03-2015 20:17:00  03-03-2015 20:22:00    2  
YYYY    03-03-2015 20:21:00  03-03-2015 20:27:00    1  

此文件的输出(RESULT)是 -

Store   Start                End                  Mins of Type 2 only  
XXXX    02-03-2015 10:04:00  02-03-2015 10:12:00  00:01:30  
YYYY    02-03-2015 20:04:00  02-03-2015 20:27:00  00:05:00

因此,对于每个商店(商店在表格中是唯一的),我将使用重叠卷起间隔以创建单个间隔。

现在,对于每个store,我想找到纯粹类型2的时间段。因此,如果存在重叠,则类型1具有优势。我想要为类型2留下任何剩余时间的总和。

我已编写此代码但无法解决重叠问题:

alter table [DATA] add Outage float;

update [DATA]
set Outage = DATEDIFF(SECOND,[Start],[END])

alter table [RESULT] add [Outage_Type1 (%)] float,[Outage_Type2 (%)] float;

UPDATE [RESULT]
SET [Outage_Type1 (%)]=(Select (DATEDIFF(SECOND,Min([Start]),Max([END]))) from [DATA] where ([DATA].[Type]= '1') and ([RESULT].[Site_ID] = [DATA].[Site_ID]) and ([DATA].[Start] between [RESULT].[Start] and [RESULT].[End]) and ([DATA].[END] between [RESULT].[Start] and [RESULT].[End]))
 from [RESULT]

UPDATE [RESULT]
SET [Outage_Type2 (%)]=(Select (DATEDIFF(SECOND,Min([Start]),Max([END]))) from [DATA] where ([DATA].[Type]= '2') and ([RESULT].[Site_ID] = [DATA].[Site_ID]) and ([DATA].[Start] between [RESULT].[Start] and [RESULT].[End]) and ([DATA].[END] between [RESULT].[Start] and [RESULT].[End]))
from [RESULT]

UPDATE [RESULT]
SET [Outage_Type1 (%)]=0 where [Outage_Type1 (%)] is null;

UPDATE [RESULT]
SET [Outage_Type2 (%)]=0 where [Outage_Type2 (%)] is null;

alter table [RESULT] add Outage float;

update [RESULT]
set Outage = DATEDIFF(SECOND,[Start],[END])

UPDATE [RESULT]
SET [Outage_Type1 (%)]=Case when [Outage_Type1 (%)]<>0 then ([Outage_Type1 (%)]*100/Outage) 
            when [Outage_Type1 (%)]=0 then 0 End;

UPDATE [RESULT]
SET [Outage_Type2 (%)]=Case when [Outage_Type2 (%)]<>0 then ([Outage_Type2 (%)]*100/Outage) 
            when [Outage_Type2 (%)]=0 then 0 End;

alter table [RESULT] drop column outage;

0 个答案:

没有答案