SQL table 中任何 ID 之间的时间和超时冲突

SQL time in & time out clashes between any ids in table

我正在尝试在我的 table 中创建两个字段,显示一个视频的时间是否与任何另一个视频的时间冲突,以及哪个视频的时间冲突。

示例数据:

SELECT vid, timein, timeout
FROM mytable

vid timein                      timeout
1   2015-04-15 06:00:00.000     2015-04-16 17:00:00.000
2   2015-04-17 03:00:00.000     2015-04-17 18:00:00.000
3   2015-04-16 16:00:00.000     2015-04-17 06:00:00.000
4   2015-04-12 12:00:00.000     2015-04-12 22:00:00.000
5   2015-03-25 01:00:00.000     null

期望的输出:

vid timein                      timeout                     Clash   Clashwith
1   2015-04-15 06:00:00.000     2015-04-16 17:00:00.000     CLASH   3
2   2015-04-17 03:00:00.000     2015-04-17 18:00:00.000     CLASH   3
3   2015-04-16 16:00:00.000     2015-04-17 06:00:00.000     CLASH   1, 2
4   2015-04-12 12:00:00.000     2015-04-12 22:00:00.000     OK
5   2015-03-25 01:00:00.000     null                        OK

我尝试过的:

SELECT vid, timein, timeout,
CASE WHEN (SELECT tin.timein 
           FROM mytable tin 
           WHERE tin.vid = mytable.vid 
           AND mytable.timeout IS NOT NULL) 
           BETWEEN mytable.timein AND mytable.timeout
     THEN 'CLASH' 
     ELSE 'OK' 
     END AS inclash,
CASE WHEN (SELECT tout.timeout 
           FROM mytable tout 
           WHERE tout.vid = mytable.vid 
           AND mytable.timeout IS NOT NULL) 
           BETWEEN mytable.timein AND mytable.timeout
     THEN 'CLASH' 
     ELSE 'OK' 
     END AS outclash
FROM mytable

这不起作用,因为它对所有结果都产生了冲突,而且我也不知道如何与写入的列发生冲突。

你可以用一个简单的 apply() 来完成,要连接所有冲突的 ID,你可以使用 xml 技巧:

select
    t1.vid,
    t1.[timein],
    t1.[timeout],
    case when c.Clashwith is not null then 'CLASH' else 'OK' end as Clash,
    c.Clashwith
from mytable as t1
    outer apply (
        select
            stuff(
                (
                    select ',' + cast(t2.vid as nvarchar(max))
                    from mytable as t2
                    where
                        t2.vid <> t1.vid and
                        t2.[timein] <= t1.[timeout] and
                        t2.[timeout] >= t1.[timein]
                     for xml path(''), type
                ).value('.', 'nvarchar(max)')
            ,1,1,'') as Clashwith
    ) as c

sql fiddle demo