If you are using SQL Server 2012 then you can use the new LAG functionality which will allow you to check the previous record.
Given that you have a sequence you just need to check that that the previous entry was the opposite of the row you are examining, allowing for nulls.
with checking as (
SELECT SeqID, PunchTime,
LAG(t.Type) OVER (ORDER BY t.SeqID) PreviousValue,
t.Type,
LEAD(t.Type) OVER (ORDER BY t.SeqID) NextValue
FROM tracking t )
SELECT t.*
FROM tracking t
INNER JOIN checking c ON t.SeqID = c.SeqID
WHERE ISNULL(PreviousValue,-1) <> c.Type
order by t.SeqID
Points of interest - I used
ISNULL(PreviousValue, -1)
to make sure the nulls at the start and end of the temporary table ([checking]) were definitely different to the type of those rows.
- I've also included the
LEAD
code so you can see how to "look ahead" to the next row.
This produced the following results:
SEQID DEVICESID EMPLOYEEID TYPE PUNCHTIME
1 2 624 0 July, 01 2014 09:00:08+0000
2 2 624 1 July, 02 2014 01:00:18+0000
3 2 624 0 July, 02 2014 08:55:11+0000
5 2 624 1 July, 02 2014 17:00:14+0000
EDIT - For completeness here is an equivalent solution for SQL 2008 using Common Table Expression
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY t.SeqID),
t.Type,
t.SeqID
FROM tracking t )
SELECT CTE.SeqID,
prev.Type PreviousValue, CTE.Type, nex.Type NextValue
INTO ##checking
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
SELECT t.*
FROM tracking t
INNER JOIN ##checking c ON t.SeqID = c.SeqID
WHERE ISNULL(PreviousValue,-1) <> c.Type
order by t.SeqID
This article may prove useful :
Common Table Expressions(CTE) in SQL SERVER 2008[
^] and here is a good example on using LAG and LEAD -
SQLauthority blog[
^]