Return only records where there is a difference in FTE or Position title field.
I have a table of employee data with fields employee#, job#, start date FTE and Position. For each employee and job I only want to return records where there is a change in FTE or Position
Record,Employee#,Job#,Start Date, FTE,Position
1, 1000, 01, 01/01/2011, 100, A
2, 1000, 01, 01/06/2011, 100, A
3, 1000, 01, 01/07/2011, 80, B
4, 1000, 01, 01/08/2011, 80, C
5, 1000, 01, 01/10/2011, 80, C
6, 1000, 02, 01/01/2011, 20, A
7, 1000, 02, 01/05/2011, 20, A
8, 1000, 02, 01/08/2011, 20, B
The query should return records 1, 3,4,6,8. (These are the only records were FTE and Position are different from the previous row)
Depends on what database you are using. If youre using Oracle the the following should do the trick:
In the sub-query you can see the use of the Oracle analytical function LAG – A good article on this can be found here. This function is ordering the rows by ‘record’ and then selecting the previous rows fte or position. In the outer query the WHERE clause is specifying conditions to only return the row if the current fte is not equal to the previous rows fte or the same with position. In addition, due to the way oracle treats NULL values, additional conditions in the WHERE clause also return the row if either value are NULL.
Whilst I have provided a solution, I must question why you are doing this, if given more information there is probably a better way to satisfy your solution, returning every row where there is a change seems like it might be leading on to bigger things. If you can provide more information as to what you are doing then maybe a better solution can be reached.