SCADA表每天的运行时间

时间:2014-12-03 03:23:21

标签: sql sql-server tsql sql-server-2008-r2

我有SCADA数据,如:

event_time  status
1/01/2011 5:07:34   Running
1/01/2011 5:14:22   Stopped
2/01/2011 13:13:21  Running
2/01/2011 14:14:22  Stopped

显示电机启动信号和电机停止信号。

如何生成如下所示的表格,显示每天的总分钟数:

date   runtime_mins    
1/1/2011 32:00
2/1/2011 54:00
3/1/2011 34:00

感谢您的任何想法!

2 个答案:

答案 0 :(得分:1)

您需要获取下一个值,您可以使用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;

答案 1 :(得分:0)

这应该有用。

;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)