sql - MySQL select first and last records from a series of same value -
i have table this
id status timestamp 1 1 2012-02-03 00:00:05 2 1 2012-02-03 00:00:10 3 0 2012-02-03 00:00:15 4 0 2012-02-03 00:00:20 5 0 2012-02-03 00:00:25 6 1 2012-02-03 00:00:30 7 1 2012-02-03 00:00:35 8 1 2012-02-03 00:00:40 9 0 2012-02-03 00:00:45 10 1 2012-02-03 00:00:50 i using mysql. need sql query or stored procedure selects rows ids (1,2,3,5,6,8,9,10). ie need first , last record series of same "status" records after ordering timestamp. doable?. help!!!
drop table if exists my_table; create table my_table (id int not null auto_increment primary key ,status tinyint not null ,timestamp timestamp not null ); insert my_table values (1 ,1 ,'2012-02-03 00:00:05'), (2 ,1 ,'2012-02-03 00:00:10'), (3 ,0 ,'2012-02-03 00:00:15'), (4 ,0 ,'2012-02-03 00:00:20'), (5 ,0 ,'2012-02-03 00:00:25'), (6 ,1 ,'2012-02-03 00:00:30'), (7 ,1 ,'2012-02-03 00:00:35'), (8 ,1 ,'2012-02-03 00:00:40'), (9 ,0 ,'2012-02-03 00:00:45'), (10 ,1 ,'2012-02-03 00:00:50'); select a.id start , min(c.id) end my_table left join my_table b on b.status = a.status , b.id = a.id - 1 left join my_table c on c.status = a.status , c.id >= a.id left join my_table d on d.status = a.status , d.id = c.id + 1 b.id null , c.id not null , d.id null group a.id; +-------+------+ | start | end | +-------+------+ | 1 | 2 | | 3 | 5 | | 6 | 8 | | 9 | 9 | | 10 | 10 | +-------+------+ here's fiddle same
Comments
Post a Comment