Okay I have a table that looks as following:
id | status(bool) | devicename(text) | datetime (timestamp) | kwh(float)
1 | 0 | Light | 2012-04-17 00:40:12 | 0.6
is a typical example of the data. Now I want to work out how long the device has been on (status) for. I would like to use the TIMEDIFF(expr1,expr2)
between each set of status {1, 0}
as I believe it's perfect for this kind of task.
I tried to create a query where I can get the pairs of 1->0 and work out their corresponding time differences. There is the added problem whereby if the last value is on, I would like to have it work out the time difference between the ON time point and the current time. I know there is an easier way to do this than manually using php to analyse the table results.
Many Thanks
Well, if you really want it in MySQL:
SET @total = 0, @lasttime = 0, @laststatus = 0;
SELECT IF(`status`=0,
@total := IF(@lasttime=0,
0,
@total+TIMEDIFF(`datetime`,@lasttime)
),
@lasttime := `datetime`
), (@laststatus := `status`) FROM `table`;
SET @total = @total + IF(@laststatus=1,TIMEDIFF(NOW(),@lasttime),0);
SELECT @total AS `result`
Honestly it'd just be easier to select all the rows and let PHP process it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.