Given a table with employee statuses and effective dates, how can I retrieve just the data that reflects a change in status?
For example, given the following structure:
DECLARE @STATUSES TABLE(
EMPLOYEE_ID INT NOT NULL,
EFFECTIVE_DATE DATE NOT NULL,
STATUS_CODE CHAR(1) NOT NULL
)
INSERT @STATUSES VALUES (1, '2012-01-01', 'A')
INSERT @STATUSES VALUES (1, '2012-02-28', 'A')
INSERT @STATUSES VALUES (1, '2012-03-01', 'T')
INSERT @STATUSES VALUES (2, '2012-01-01', 'A')
INSERT @STATUSES VALUES (2, '2012-02-14', 'A')
INSERT @STATUSES VALUES (2, '2012-03-10', 'A')
INSERT @STATUSES VALUES (3, '2012-02-01', 'A')
INSERT @STATUSES VALUES (3, '2012-03-17', 'A')
INSERT @STATUSES VALUES (3, '2012-03-18', 'T')
INSERT @STATUSES VALUES (3, '2012-04-01', 'A')
INSERT @STATUSES VALUES (4, '2012-03-01', 'A')
What query can be used to result in the following?
EMPLOYEE_ID EFFECTIVE_DATE STATUS_CODE
1 2012-01-01 A
1 2012-03-01 T
2 2012-01-01 A
3 2012-02-01 A
3 2012-03-18 T
3 2012-04-01 A
4 2012-03-01 A
In other words, I want to leave out those records that have the same employee id and status code as the one before it, if one exists with an earlier effective date. Notice that employee 1 is listed only twice because there were only two actual changes in status–the one on 2012-02-28 is inconsequential since the status didn’t change from the earlier date. Also notice that employee 2 is listed just once since his status never changed despite there being three records. Only the earliest date is shown for each change.
With some further experimenting, it looks like this will do what I want.