Determine on time between 1 to 0 transitions

依然范特西╮ 提交于 2021-02-18 12:12:14

问题


My table indicates a pump ON/OFF status as follows

Value   timestamp
1       2013-09-01 00:05:41.987
0       2013-09-01 00:05:48.987
1       2013-09-01 00:05:59.987
0       2013-09-01 00:06:15.987
1       2013-09-01 00:06:34.987
etc etc. 

I need a MSSQL query that can take a months worth of these and tell me the number of minutes ON (1) and number in minutes OFF (0) i.e. duty cycle


回答1:


Using CTE and RowNumber() function Fiddle demo:

declare @date date = '20130925'

;with cte as (
  select value, timestamp, row_number() over(order by timestamp) rn
  from table1
)
select c1.value, sum(datediff(second, c1.timestamp, c2.timestamp)) diffInSeconds
from cte c1 join cte c2 on c1.rn = c2.rn -1
where month(c1.timestamp) = month(@date) and month(c2.timestamp) = month(@date)
group by c1.value



回答2:


Try this (SQL Server 2012):

SELECT value, SUM(sec) AS sec
FROM
(
        SELECT value, ISNULL(DATEDIFF(SECOND, timestamp,
                LEAD(timestamp,1) OVER (ORDER BY timestamp)
                ),0) sec
        FROM tbl
) t
GROUP BY value;



回答3:


for sql server 2005 and later @start and @end declare s the time range you need to check

with data as
(
    select
        value,
        timestamp,
        row_number() over (timestamp) as aa
    from
        data
    where
        timestamp between @start and @end
)
select
    onPayload,
    datediff(s,@start,@end)-onPayload as offPayload
from
(   
select
    sum(datediff(s,s.timestamp, e.timestamp)) as onPayload,
from
    data as s
inner join
    data as e
on
    s.aa = e.aa-1
where
    s.value=1
and
    e.value=0
) as a


来源:https://stackoverflow.com/questions/19575244/determine-on-time-between-1-to-0-transitions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!