0

I'm having trouble trying to retrieve data from mySQL table. The table holds all the lap times from a racing event by all the participants. The table has multiple entries for each race. I would like to select each participant's best lap time, however I'm not sure how to get rid each participant's duplicates.

I've tried the following statement.

SELECT *
FROM   laptimes
GROUP  BY laptime,
          username 

The table looks like this:

lap username    laptime
2   Blackvault  1200.000    
1   Blackvault  1234.000    
3   Elmo        1235.000    

I'd like to display only lap 2 of Blackvault and Elmo's only lap. The SQL will need to be generic as there could be N number of racers and N number laps.

Any help is appreciated.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
Blackvault
  • 319
  • 5
  • 9
  • [SQL Group By with an Order By][1] [1]: http://stackoverflow.com/questions/27983/sql-group-by-with-an-order-by This might be helpful. – F4b May 24 '15 at 17:42

2 Answers2

2

If you want to get the original data row (in MySQL), then you need to get the best time and connect it to the original data. Here is a method using join:

select lt.*
from laptimes lt join
     (select username, min(laptime) as laptime
      from laptimes
      group by username
     ) lu
     on lu.username = lt.nusername and lu.laptime = lt.laptime;

If you don't need the id (or other columns), then the subquery might be sufficient for your purposes.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

If you need to select only best laptime then you need this :

SELECT lap,username, min(laptime) as laptime
FROM laptimes 
GROUP BY username
Hotdin Gurning
  • 1,821
  • 3
  • 15
  • 24