I have a SQL query that retrieves data from a table that lists athletes’ 100- and 200-meter race times. The query only retrieves the best race time of each athlete based on the athlete_id, it also wants to know if the race-time is a 100 or 200 meter-time (event_code).
So a runner can have several race-times but the query only gets the best race-time from each runner at each event.
The problem is that if an athlete have done exactly the same best race time two or more times, the query retrieves all those race times. How can I make sure the query only retrives one value?
Here is the code:
select r.*
from result r
inner join (
select athelete_id, min(result_time) as FastestTime
from result
where event_code = 1
group by athelete_id
) rm on r.athelete_id = rm.athelete_id and r.result_time = rm.FastestTime
It is a pain in SQL Server 2000. This would be much easier using row_number, but that requires 2005.
However, the idea is simple, you just need one more layer of subqueries:
The innermost subquery is basically your subquery. Then, this is aggregated by athelete_id, to get the minimum result_id, which is used for the final join.