Reputation: 836
I have following table
Id | Status | date
-------------------
1 | Onsite |2007
2 | Onsite |2008
3 | Onsite |2009
4 | Abroad |2010
5 | Abroad |2011
6 | Onsite |2012
7 | Abroad |2013
8 | Abroad |2014
9 | Onsite |2015
I want a query in MySQL, which returns a record when status is changed from 'Abroad' to 'Onsite'. In above case query will return me following rows:
6 | Onsite |2012
9 | Onsite |2015
Upvotes: 0
Views: 253
Reputation: 11320
Try the following query which works even if ids are not in an sequence:
SELECT *
FROM 'table_name' t
WHERE t.status = 'Onsite' and
EXISTS(SELECT t1.id
FROM 'table_name' t1
WHERE t1.status = 'Abroad' and t1.id<t.id
ORDER BY t1.id DESC
LIMIT 1,1);
Upvotes: 2