我有下表:
╔═════════════════════════╦═══╗
║ DATETIME ║ M ║
╠═════════════════════════╬═══╣
║ 2015-06-17 15:03:44.840 ║ 1 ║
║ 2015-06-17 15:03:33.940 ║ 1 ║
║ 2015-06-17 15:03:32.950 ║ 1 ║
║ 2015-06-17 15:03:22.060 ║ 1 ║
║ 2015-06-17 15:03:11.210 ║ 0 ║
║ 2015-06-17 14:50:12.950 ║ 0 ║
║ 2015-06-17 13:50:12.850 ║ 0 ║
║ 2015-06-17 12:50:12.790 ║ 0 ║
║ 2015-06-17 12:49:10.410 ║ 1 ║
║ 2015-06-17 12:48:59.510 ║ 1 ║
║ 2015-06-17 12:48:48.630 ║ 1 ║
║ 2015-06-17 12:48:37.730 ║ 1 ║
║ 2015-06-17 12:48:26.830 ║ 1 ║
║ 2015-06-17 12:48:15.940 ║ 1 ║
║ 2015-06-17 12:48:14.950 ║ 1 ║
║ 2015-06-17 12:48:04.060 ║ 1 ║
║ 2015-06-17 12:47:53.170 ║ 1 ║
║ 2015-06-17 12:47:42.280 ║ 0 ║
║ 2015-06-17 12:44:14.350 ║ 0 ║
║ 2015-06-17 12:43:08.970 ║ 1 ║
╚═════════════════════════╩═══╝
我的目标是选择零和一组,并计算日期和时间的差异。
我怎样才能做到这一点?
我的最终结果是能够找到连续出现的零并计算相应的持续时间。
答案 0 :(得分:3)
这是一个解决方案:
DECLARE @t TABLE ( d DATETIME, m INT )
INSERT INTO @t
VALUES ( '2015-06-17 15:03:44.840', 1 ),
( '2015-06-17 15:03:33.940', 1 ),
( '2015-06-17 15:03:32.950', 1 ),
( '2015-06-17 15:03:22.060', 1 ),
( '2015-06-17 15:03:11.210', 0 ),
( '2015-06-17 14:50:12.950', 0 ),
( '2015-06-17 13:50:12.850', 0 ),
( '2015-06-17 12:50:12.790', 0 ),
( '2015-06-17 12:49:10.410', 1 ),
( '2015-06-17 12:48:59.510', 1 ),
( '2015-06-17 12:48:48.630', 1 ),
( '2015-06-17 12:48:37.730', 1 ),
( '2015-06-17 12:48:26.830', 1 ),
( '2015-06-17 12:48:15.940', 1 ),
( '2015-06-17 12:48:14.950', 1 ),
( '2015-06-17 12:48:04.060', 1 ),
( '2015-06-17 12:47:53.170', 1 ),
( '2015-06-17 12:47:42.280', 0 ),
( '2015-06-17 12:44:14.350', 0 ),
( '2015-06-17 12:43:08.970', 1 );
WITH cte
AS ( SELECT * ,
ROW_NUMBER() OVER ( ORDER BY d DESC )
- ROW_NUMBER() OVER ( PARTITION BY m ORDER BY d DESC ) rn
FROM @t
)
SELECT ROW_NUMBER() OVER(ORDER BY MIN(d) desc) AS [#],
DATEDIFF(mi, MIN(d), MAX(d)) / 60 Hours,
DATEDIFF(mi, MIN(d), MAX(d)) - ( DATEDIFF(mi, MIN(d), MAX(d)) / 60 ) * 60 Minutes
FROM cte
WHERE m = 0
GROUP BY rn
输出:
# Hours Minutes
1 2 13
2 0 3
在CTE内部有一些间隙和岛屿解决方案,然后按等级分组并计算结果。