mysql - Sql to find timediff between two rows based on ID -
the subject of question not explanatory, sorry that.
ya question follows: have database structure below pk primary key, id multiple many rows.
+------+------+---------------------+ | pk | id | value | +------+------+---------------------+ | 99 | 1 | 2013-08-06 11:10:00 | | 100 | 1 | 2013-08-06 11:15:00 | | 101 | 1 | 2013-08-06 11:20:00 | | 102 | 1 | 2013-08-06 11:25:00 | | 103 | 2 | 2013-08-06 15:10:00 | | 104 | 2 | 2013-08-06 15:15:00 | | 105 | 2 | 2013-08-06 15:20:00 | +------+------+---------------------+
what need is, value difference between first 2 rows (which ordered value) each group (where group id). according above structure need timediff(value100, value99) [ id 1 group] , timediff(value104, value103) [ id 2 group]
i.e. value difference of time ordered value 1st 2 rows in each group.
one way can think 3 self joins (or 3 sub queries) find first 2 in 2 of them , , third query subtracting it. suggestions?
looks bit wierd... can try way
set @previous = 0; set @temp = 0; set @tempid = 0;
above step may not needed .. make sure nothing goes wrong
select pkid, id, diff, valtemp ( select if(@previousid = id, @temp := @temp + 1, @temp := 1) occ, @previousid := id, timediff(`value`, @previous) diff, pk, id, `value`, @previous := `value` testtable) occ = 2
Comments
Post a Comment