我有 SCADA </跨度> 数据如:
event_time状态1/01/2011 5:07:34跑步1/01/2011 5:14:22停了下来2/01/2011 13:13:21跑步2/01/2011 14:14:22停了下来
其中显示了电机启动信号,以及……
您需要获取下一个值,您可以使用它 outer apply :
outer apply
select s.date, sum(datediff(seconds, s.date, snext.date) / 60.0) as runtime_minutes from scada s outer apply (select top 1 date from scada s2 where s2.date > s.date and s2.status = 'Stopped' order by s2.date desc ) snext where s.status = 'Running' group by s.date;
这应该工作。
;WITH CTE( [event_time], [status]) AS ( SELECT CAST('1/01/2011 5:07:34' AS DATETIME) , 'Running' UNION ALL SELECT '1/01/2011 5:14:22', 'Stopped' UNION ALL SELECT '2/01/2011 13:13:21', 'Running' UNION ALL SELECT '2/01/2011 14:14:22', 'Stopped' UNION ALL SELECT '3/01/2011 13:13:21', 'Running' UNION ALL SELECT '3/01/2011 14:14:22', 'Stopped' ) , cte_Running AS ( SELECT * FROM CTE WHERE [CTE].[status] = 'Running' ) , cte_Stopped AS ( SELECT * FROM CTE WHERE [CTE].[status] = 'Stopped' ) SELECT CONVERT(VARCHAR(10), [r].[event_time], 101) AS [date] , DATEDIFF(MINUTE, [r].[event_time], [s].[event_time]) AS [runtime_mins] FROM cte_Running AS r INNER JOIN cte_Stopped AS s ON CAST(r.event_time AS DATE) = CAST(s.event_time AS DATE)