I have a set with data in a SQL Server database and I need to calculate uptime of a machine. I’m using two variables to determine uptime or downtime. These two variables are machine_ON and failure(s). machine_ON is only one variable in the database, failure can be 64 different failures, but all indicates as fx_x.
The status information of these variables is stored in the database as follow:
timestamp failurebitNr timestampOutOfAlarm
2012-01-17 10:38:58.000 f1_14 2012-01-17 10:39:05.000
Meaning: failure f1_14 was active from 2012-01-17 10:38:58.000 until 2012-01-17 10:39:05.000
Also the machine_ON state is saved in the same table on the same way, only the failurebitNr has a different value [t2_13].
So to determine the uptime, I need to get the timediff between timestamp and timestampOutOfAlarm where failurebutNr = 't2_13' minus any failure time.
So for example I have those rows in my database:

This should give the following graphical representation:

Green is uptime, red is downtime.
I’m used to work with PHP and than use a while loop and file some array’s and do other scripting. But now I need to do this all in a SQL Server database in query ways…
So, how can I calculate the uptime (green) and downtime (red)?
UPDATE
I’ve tried to get the time in seconds that the machine is ON. I used this query:
<!-- language: lang-sql -->
DECLARE @startDate datetime
DECLARE @endDate datetime
DECLARE @projectNr int
DECLARE @MachineNr nvarchar(10)
SET @startDate = '2012-01-01 00:00:00.000'
SET @endDate = '2012-02-01 00:00:00.000'
SET @projectNr = '1234567'
SET @MachineNr = '2'
SELECT
DATEDIFF("SECOND",
CASE WHEN timestamp < @startDate
THEN @startDate
ELSE timestamp
END,
CASE WHEN timestampOutOfAlarm > @endDate OR timestampOutOfAlarm IS NULL
THEN @endDate
ELSE timestampOutOfAlarm
END) AS Uptime
FROM
[table]
WHERE
timestamp < @endDate
AND (timestampOutOfAlarm > @startDate OR timestampOutOfAlarm IS NULL)
AND fileProjectNr = @projectNr
AND fileProjectMachineNr = @MachineNr
AND (failureBitNr = 't2_13' AND failureBitValue = '1')
Problem solved:
I did it in 2 stored procedures, or Query’s. One for getting the “ON” time and one for getting all the “DOWN” time within the “ON” time. Whith those two times I can calculate the uptime, downtime, maintenance time.
Query for ON time:
Query for Downtime during ON time: