5

我的表指示泵的开/关状态如下

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. 

我需要一个 MSSQL 查询,它可能需要几个月的时间,并告诉我开启 (1) 的分钟数和关闭 (0) 的分钟数,即占空比

4

3 回答 3

1

使用CTERowNumber() function 小提琴演示

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
于 2013-10-24T20:11:05.123 回答
0

对于 sql server 2005 及更高版本,@start 和 @end 声明您需要检查的时间范围

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
于 2013-10-24T20:06:12.287 回答
0

试试这个(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;
于 2013-10-24T20:06:43.913 回答