I’m really struggling creating a select statement that will return the record with the fastest time for each user.
If there is a tie on number if seconds, the lowest ‘clicks’ should be selected.
If I have the following records in my table
user seconds clicks
1 10.23 10
1 10.12 12
1 10.12 14
2 12.11 16
3 12.34 18
3 12.00 16
I need the lowest time and clicks for each user, so I need a query to return
user seconds clicks
1 10.12 12
2 12.11 16
3 12.00 16
The query I’ve tried is
select user, min(seconds), min(clicks) from mytable group by user
But it selects seconds 10.12 and clicks 10 for user 1 which is incorrect.
Can I do this in 1 query?
This is a variation of the
greatest-n-per-groupproblem that comes up frequently.Explanation:
We want
mto be the row for each user that has the lowest seconds, or if there’s a tie for lowest seconds, the lowest clicks. In other words, there should be no other row for that user with a lower seconds or a lower clicks.Use an exclusion join trying to find any row with lower seconds or lower clicks. If no such row is found, then
mis the one with the lowest values.It’s still possible to result in a tie and return more than one row for a user, if there’s more than one row with the least seconds and least clicks. In that case, you need to resolve the tie with some other column, hopefully one that is unique.
Example: