I have a table called Objects which contains some files, say:
- User
- Teacher
There is another table (States) which holds the possible states of these objects, like:
- Active
- Idle
- Teaching
- Resting
- Authoring
And there is a third table (junction table) which logs each state change of each object. In this third table (ObjectStates) records are like:
- 1, 1, DateTime1 (User was active on DateTime1)
- 2, 5, DateTime2 (Teacher was authoring on DateTime2)
etc.
Now, what I want is a query to get each object, with its latest state (not state history). It’s possible to get this result using cursors, or using Cross Apply command. However, I’d like to know if there is any other way to get the latest states of each object from these three tables? Because cursors are costy.
Using the
row_number()windowing function…If you can’t use
row_numberbecause you’re on SQL 2000, for example, you can use a join on amax/group byquery.