我有一個表與日期範圍我需要其行之間的重疊時期(以小時爲單位)的總和。TSQL從日期時間範圍獲得重疊期
這是一個模式例如:
create table period (
id int,
starttime datetime,
endtime datetime,
type varchar(64)
);
insert into period values (1,'2013-04-07 8:00','2013-04-07 13:00','Work');
insert into period values (2,'2013-04-07 14:00','2013-04-07 17:00','Work');
insert into period values (3,'2013-04-08 8:00','2013-04-08 13:00','Work');
insert into period values (4,'2013-04-08 14:00','2013-04-08 17:00','Work');
insert into period values (5,'2013-04-07 10:00','2013-04-07 11:00','Holyday'); /* 1h overlapping with 1*/
insert into period values (6,'2013-04-08 10:00','2013-04-08 20:00','Transfer'); /* 6h overlapping with 3 and 4*/
insert into period values (7,'2013-04-08 11:00','2013-04-08 12:00','Test'); /* 1h overlapping with 3 and 6*/
而其撥弄:http://sqlfiddle.com/#!6/9ca31/10
我期望的8H重疊小時的總和: 1H(ID 5以上的id 1) 6H(ID 6以上編號3和4) 1h(id 7 over id 3 and 6)
我檢查了這個:select overlapping datetime events with SQL但似乎沒有做我所需要的。
謝謝。
有一個bug ......嘗試添加另一個重疊記錄:插入週期值(7,'2013-04-08 10:00','2013-04-08 11:00','測試');我預計只有另外1小時的重疊總和。 – Tobia 2013-04-09 08:22:55
我認爲這個查詢需要一個cte表達式 – Tobia 2013-04-09 08:38:28
這不能處理所有情況,例如:339989 \t 2015-01-20 00:00:00 \t 2015-05-10 00:00:00 2015-01 -20 00:00:00 \t 2015-08-19 00:00:00 2015-01-20 00:00:00 \t 2015-08-19 00:00:00 2015-05-11 00:00:00 \t 2015-08-19 00:00:00 2015-08-20 00:00:00 \t 2015-12-06 00:00:00 2015-08-20 00: 00:00 \t 2015-12-06 00:00:00 – 2016-06-06 20:41:27