我正在尝试在我的表格中创建两个字段,以显示视频的时间是否与任何其他视频时间冲突,以及视频的冲突。
示例数据:
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
这不起作用,因为它会对所有结果发生冲突,我也不知道如何与列编写冲突。
答案 0 :(得分:3)
你可以用一个简单的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 强>