I have a table (SQL Server 2005) with the following columns:
State:
- StateId INT PRIMARY KEY
- VehicleId INT
- ValidFromDate DATETIME
For each VehicleId
there can be several rows in this table. I want to select the currently valid states (with a date parameter). There can be at most one valid state for each vehicle (the one with the highest ValidFromDate
less than the date parameter).
If the table looks like this:
StateId VehicleId ValidFromDate
--- --- ---
1 1 2009-01-01
2 1 2009-06-02
3 1 2009-11-03
4 2 2009-06-04
5 3 2009-10-05
And @Date = '2009-08-14'
I want the query to produce the following result:
StateId VehicleId ValidFromDate
--- --- ---
2 1 2009-06-02
4 2 2009-06-04
I think that the following query produces the correct result:
SELECT * FROM State s1
WHERE s1.StateId IN (SELECT TOP 1 StateId
FROM State s2
WHERE s2.ValidFromDate <= @Date AND s1.VehicleId = s2.VehicleId
ORDER BY s2.ValidFromDate DESC, s2.StateId DESC)
But there must be a better way to do this, using some kind of grouping clause, right? It doesn't feel right to use a subquery of the same table.