WITH RECURSIVE rq_range AS ( SELECT DISTINCT rq from cars ), track_combinations AS ( -- Extract unique human-readable track_id and track_type combinations SELECT DISTINCT track_id, track_type FROM car_track_times ), ranked_cars AS ( SELECT rq_range.rq AS max_rq, t.track_id, t.track_type, c.rq, c.brand, c.onlyName, c.year, t.configuration, t.time, ROW_NUMBER() OVER ( PARTITION BY rq_range.rq, t.track_id, t.track_type ORDER BY t.time ASC ) AS rank FROM rq_range CROSS JOIN track_combinations tc JOIN car_track_times t ON tc.track_id = t.track_id AND tc.track_type = t.track_type JOIN cars c ON t.car_rid = c.rid WHERE t.time > 0 -- Exclude invalid times AND t.time IS NOT NULL AND c.rq <= rq_range.rq ) SELECT rq, brand, onlyName, year, Count(time) FROM ranked_cars WHERE rank = 1 -- Only the best car per combination GROUP BY brand, onlyName, year ORDER BY rq, brand, onlyName, year;