I´m using SQL Server 2008, how can I calculate the time between On and Off status? I have the following table (ordered by timestamp):
ID | EQUIP_ID | TIMESTAMP | STATUS (1 on/0 off)
1 | 1 | 21/05/2012 13:00:00 | 1
3 | 1 | 21/05/2012 13:04:00 | 1
4 | 1 | 21/05/2012 13:05:00 | 0
6 | 1 | 21/05/2012 13:09:00 | 1
7 | 1 | 21/05/2012 13:10:00 | 1
9 | 1 | 21/05/2012 13:12:00 | 1
10 | 1 | 21/05/2012 13:13:00 | 0
10 | 1 | 21/05/2012 13:14:00 | 1
10 | 1 | 21/05/2012 13:15:00 | 0
And I expect a result like this:
EQUIP_ID | START | END | STATUS
1 | 21/05/2012 13:00:00 | 21/05/2012 13:05:00 | 1 (WORKING)
1 | 21/05/2012 13:05:00 | 21/05/2012 13:09:00 | 0 (STOPPED)
1 | 21/05/2012 13:09:00 | 21/05/2012 13:13:00 | 1
1 | 21/05/2012 13:13:00 | 21/05/2012 13:14:00 | 0
1 | 21/05/2012 13:14:00 | 21/05/2012 13:15:00 | 1
I’ve tried some functions for gaps and islands but didn’t work and I don’t know what I’m missing…
Here’s my take on it. Assuming your table is called “MyData”:
It makes use of the
ROW_NUMBER()function to determine changes in statuses for eachEQUIP_ID. Then it simply finds when a status started (MIN([TIMESTAMP])), then I match it up with the time it ended (MAX([TIMESTAMP])) in the next row (see the self-join onRowNum). TheWHEREeliminates the last row which has no end time. The results I get are: