How to pair date rows in mysql -
how pair rows imperfecty in mysql? imperfect, meaning rows not paired in , out. sometimes, there 2 in 1 out or no out @ or 2 or more out 1 in or no in @ all. table this:
| id | action | date | +----+--------+---------------------+ | 1 | in | 19.1.2012 15:41:52 | | 1 | out | 19.1.2012 15:55:52 | | 2 | in | 19.2.2012 15:55:52 | | 2 | out | 19.2.2012 17:55:53 | | 1 | in | 19.3.2012 15:55:54 | | 1 | in | 19.3.2012 17:55:55 | | 1 | out | 19.3.2012 19:55:56 | | 3 | in | 19.4.2012 15:55:57 | | 3 | out | 19.4.2012 17:55:58 | | 3 | out | 19.4.2012 19:55:59 | +----+--------+---------------------+
the desired result this:
+----+--------+---------------------+ | id | action | date | +----+--------+---------------------+ | 1 | in | 19.1.2012 15:41:52 | | 1 | out | 19.1.2012 15:55:52 | | 2 | in | 19.2.2012 15:55:52 | | 2 | out | 19.2.2012 17:55:53 | | 1 | in | 19.3.2012 17:55:55 | | 1 | out | 19.3.2012 19:55:56 | | 3 | in | 19.4.2012 15:55:57 | | 3 | out | 19.4.2012 17:55:58 | +----+--------+---------------------+
this best desireed result
+----+---------------------+---------------------+ | id | date_in | date_out | +----+---------------------+---------------------+ | 1 | 19.1.2012 15:41:52 | 19.1.2012 15:55:52 | | 2 | 19.2.2012 15:55:52 | 19.2.2012 17:55:53 | | 1 | 19.3.2012 17:55:55 | 19.3.2012 19:55:56 | | 3 | 19.4.2012 15:55:57 | 19.4.2012 17:55:58 | +----+---------------------+---------------------+
here code, yields different result, can figure out error is? enter code here select c.e_id , cast(c.in_time datetime) in_time , c.out_time ( select if(@prev_id = d.id,@in_time,@in_time:=null) reset_in_time , @in_time := if(d.action = 'in',d.date,@in_time) in_time , if(d.action = 'out',d.date,null) out_time , @prev_id := d.id id ( select id, date_, action e join (select @prev_id := null, @in_time := null) f order id, date, action ) d ) c c.out_time not null order c.out_time enter code here
this selects in event a, out event b , uses left join
eliminate row if there exists event c same id between them; in/out times don't have in or out between them.
select a.id, a.date date_in, b.date date_out mytable join mytable b on a.id = b.id , a.date < b.date left join mytable c on a.id = c.id , c.date < b.date , c.date > a.date a.action = 'in' , b.action = 'out' , c.action null order a.date;
Comments
Post a Comment