Good afternoon - I have such a question there is a table with a list

id server_id time_date old_status new_status 100 55 2014-06-03 11:32:36 run 101 55 2014-10-03 10:15:36 run down 102 55 2014-10-06 10:33:36 down run 5604 56 2014-08-04 07:03:26 run down 

id - event number server_id - server name time_date - event time old_status - server status in the previous state new_status - modified state.

I need to know server uptime.

  • I need to know the uptime of the server, taking into account the states. What is it like? - splash58
  • I did not quite accurately put it - I have to calculate the time while the server was able to run. - dezzinto 1:56 pm
  • one
    translate all times in seconds and subtract the sum of all ups from the sum of all downs - splash58

1 answer 1

mysql

for example, as follows ( id means server identifier):

SQL feeddle

MySQL 5.6 Schema Setup :

 create table vremena (id int, v datetime, s text); insert into vremena values (55, '2014-06-03 11:32:36', 'run'), (55, '2014-10-03 10:15:36', 'down'), (55, '2014-10-06 10:33:36', 'run'), (55, '2014-08-04 07:03:26', 'down'); 

Query 1 :

 select sum( case when s = 'run' then - unix_timestamp(v) else unix_timestamp(v) end ) as vremja from vremena group by id 

Results :

 | vremja | |---------| | 5080370 | 

ms / sql

for example, as follows ( id means server identifier):

SQL feeddle

MS SQL Server 2014 Schema Setup :

 create table vremena (id int, v datetime, s varchar(4)); insert into vremena values (55, '2014-06-03 11:32:36', 'run'), (55, '2014-10-03 10:15:36', 'down'), (55, '2014-10-06 10:33:36', 'run'), (55, '2014-08-04 07:03:26', 'down'); 

Query 1 :

 select sum( case when s = 'run' then - datediff(second, '19700101', v) else datediff(second, '19700101', v) end ) as vremja from vremena group by id 

Results :

 | vremja | |---------| | 5080370 | 
  • Why group by id? throw it away. it's better to choose the times for one server - splash58
  • @ splash58, I meant the server by id. now looked - the author has id in the table too. hmm, a bit too much needs to be changed "for beauty": two pages per sqlfiddle and the answer itself. I will hope that the author will understand and so. - aleksandr barakin
  • well, the answer is that it is indecent to leave anything like that - splash58
  • @ splash58, and I added the decoding. - aleksandr barakin