找出唯一的区间
表格如下:
id num time
a 0 9:01
a 1 9:02
a 1 9:03
a 1 9:04
a 0 9:05
a 1 9:06
a 1 9:07
a 1 9:08
b 1 9:01
b 1 9:02
b 1 9:03
b 1 9:04
b 1 9:05
b 0 9:06
b 1 9:07
b 1 9:08
c 1 9:01
c 1 9:02
c 0 9:03
c 1 9:04
c 1 9:05
c 0 9:06
c 1 9:07
c 1 9:08
d 1 9:01
d 1 9:02
d 1 9:03
d 1 9:04
d 1 9:05
d 0 9:06
d 0 9:07
d 1 9:08
e 1 9:01
e 0 9:02
e 0 9:03
e 1 9:04
e 1 9:05
e 1 9:06
e 1 9:07
e 0 9:08
.. .. ...
希望找出 某段时间内 连续是1 的最长区间,而且一定保证是唯一的一个。
比如 e 9:04 9:07 全是1,而且 没有其他id 在9:04 9:07 重合。
b 9:01 9:05 与 d 9:01 9:05 也都是1 ,但是重合,所以排除.
希望 找出 e 9:04 9:07这个区间。
2000系统,
------最佳解决方案--------------------DECLARE @timestamp NVARCHAR(4)
SET @timestamp='9:07'
--create #1
IF object_id('tempdb..#1')IS NOT NULL
DROP TABLE #1
SELECT
a.id,b.num,b.time,CONVERT(INT,0) AS count_id
INTO #1
FROM t1 AS a
INNER JOIN t1 AS b ON a.id=b.id AND b.time<=@timestamp AND b.time>ISNULL((SELECT MAX(time) FROM t1 AS x WHERE x.id=b.id AND x.time<=@timestamp AND x.num=0),'')
WHERE a.time<=@timestamp
AND EXISTS(SELECT 1 FROM t1 AS x WHERE x.id=a.id AND x.time=@timestamp AND x.num=1)
GROUP BY a.id,b.num,b.time
UPDATE a
SET count_id=(SELECT COUNT(id) FROM #1 WHERE id=a.id)
FROM #1 AS a
S