2013-10-24 53 views
5
之間的時間

我的表顯示的泵ON/OFF狀態如下確定1到0的轉換

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的查詢,可以採取值得它們的幾個月,告訴我的分鐘數ON (1),並在幾分鐘內(0),即佔空比

+2

怎麼樣的終點?你想從2013-09-01 00:06:34.987'到現在最後一行代表1嗎? –

回答

0

SQL Server 2005的號碼已停用,後來 @啓動和@end聲明S上的時間範圍,則需要檢查

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

使用CTERowNumber() functionFiddle 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