was hoping some-one could help me with this:
My table is:
id Version datetime name resource
---|--------|------------|--------|---------
1 | 1 | 03/03/2009 | con1 | 399
2 | 2 | 03/03/2009 | con1 | 244
3 | 3 | 01/03/2009 | con1 | 555
4 | 1 | 03/03/2009 | con2 | 200
5 | 2 | 03/03/2009 | con2 | 500
6 | 3 | 04/03/2009 | con2 | 600
7 | 4 | 31/03/2009 | con2 | 700
I need to select each distinct “name” that has greatest value of “datetime” that less than or equal to a given date; and where the version is the maximum version if there are multiple records that satisfy the first condition.
The result if the given date were ’04/03/2009′ would be:
id Version datetime name resource
---|--------|------------|--------|---------
2 | 2 | 03/03/2009 | con1 | 244
6 | 3 | 04/03/2009 | con2 | 600
Currently I’ve created the following query, which works, but I suspect it’s not the best when it comes to performance when run on a large table:
SELECT [id], [Version], [datetime], [name], [resource]
FROM theTable
WHERE [Version] =
(
SELECT MAX(Version) FROM theTable AS theTable2 WHERE theTable.[name] = theTable2.[name]
AND theTable2.[datetime] =
(
SELECT MAX(theTable3.[datetime]) FROM theTable AS theTable3
WHERE theTable2.[name] = theTable3.[name] AND theTable3.[datetime] <= '04/03/2009'
)
)
I’d appreciate if some-one could suggest a more efficient way to do this; and if possible, provide an example:-).
Thanks in advance.
You can use PARTITION BY. This lets you basically rank the results. In your instance, you then want to select only the result with ranking 1. First, filter out the results with invalid date times (using WHERE), then in the partition, order by the columns descending (thus, the first result would be the one with the maximum datetime, and, in case of datetime tie, the maximum version as well.)