Хорошо, вот некоторые рабочее заявление
declare @t TABLE(id INT, dt DATETIME, sp int)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:05', 12)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:06', 0)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:07', 0)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:08', 0)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:09', 5)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:10', 8)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:11', 0)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:12', 0)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:13', 0)
INSERT INTO @t VALUES(1, '2015-01-17 12:00:14', 7)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:05', 10)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:06', 0)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:07', 0)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:08', 0)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:09', 12)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:10', 0)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:11', 0)
INSERT INTO @t VALUES(2, '2015-01-17 12:00:12', 10)
;
WITH cte1
AS (SELECT a.id ,
a.dt AS stdt ,
b.dt AS endt ,
a.sp ,
a.rn
FROM (SELECT * ,
1
+ ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt) AS n ,
ROW_NUMBER() OVER (ORDER BY GETDATE()) AS rn
FROM @t t1
) a
LEFT JOIN (SELECT * ,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt) AS n
FROM @t t1
) b ON b.id = a.id
AND b.n = a.n
),
cte2
AS (SELECT t1.id ,
t1.stdt ,
ISNULL(t1.endt, GETDATE()) AS endt ,
t1.sp ,
t1.rn ,
SUM(t2.sp) AS sum
FROM cte1 t1
INNER JOIN cte1 t2 ON t1.rn >= t2.rn
GROUP BY t1.id ,
t1.stdt ,
t1.endt ,
t1.sp ,
t1.rn
)
SELECT id ,
MIN(stdt) ,
MAX(stdt) ,
DATEDIFF(ss, MIN(stdt), MAX(stdt))
FROM cte2
WHERE sp = 0
GROUP BY id ,
SUM
Вот результат
1 2015-01-17 12:00:06.000 2015-01-17 12:00:08.000 2
1 2015-01-17 12:00:11.000 2015-01-17 12:00:13.000 2
2 2015-01-17 12:00:06.000 2015-01-17 12:00:08.000 2
2 2015-01-17 12:00:10.000 2015-01-17 12:00:11.000 1
Вы имеете результат для автомобиля 1 12:06 to 12:08
. Но я действительно думаю, что результаты должны быть . Если это так, просто измените
SELECT id ,
MIN(stdt) ,
MAX(stdt) ,
DATEDIFF(ss, MIN(stdt), MAX(stdt))
FROM cte2
WHERE sp = 0
GROUP BY id ,
SUM
в
SELECT id ,
MIN(stdt) ,
MAX(endt) ,
DATEDIFF(ss, MIN(stdt), MAX(endt))
FROM cte2
WHERE sp = 0
GROUP BY id ,
SUM
Я не очень хорош в написании SQL запросов, я уже старался изо всех сил, но не успех. – cherisys
, какую версию sql вы используете? SELECT @@ VERSION –
Microsoft SQL Server 2008 (окончательная первоначальная версия) - 10.0.1600.22 (X64) 9 июля 2008 г. 14:17:44 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-разрядная версия) в Windows NT 6.0 (Build 6002: Service Pack 2) –
cherisys