I have the following database table (People):
+--------+--------+--------+
| Name | Age | Time |
+--------+--------+--------+
| Tim | 30 | 10:10 |
| Jill | 31 | 10:20 |
| Peter | 31 | 10:30 |
| Peter | 33 | 10:40 |
| Jack | 32 | 10:50 |
| Susan | 35 | 10:60 |
| Susan | 35 | 11:70 |
+--------+--------+--------+
Now I want to get 5 names which are the oldest from this list:
Select * FROM People ORDER BY Age DESC LIMIT 5
This will give:
| Susan | 35 | 11:70 |
| Susan | 35 | 10:60 |
| Peter | 33 | 10:40 |
| Jack | 32 | 10:50 |
| Peter | 31 | 10:30 |
Now this is not exactly what I want. We see Susan in there twice, same as Peter. I don’t want duplicate names to show up. Now we see that the 2 Susans have both the same age, so the Susan with the highest time (mm:ss) should be filter out (in this case: | Susan | 35 | 11:70 |)
Fot the 2 Peters we see that one Peter is older, so in this case the younger Peter should be filtered out (| Peter | 31 | 10:30 |)
So how would this Query look like? It should first select all, then order them by Age (oldest on top), then filter out the duplicate names where it must first look at the age (lowest gets filtered) and then at the time (highest time gets filter out) and then DESC LIMIT 5.
So the only correct result will look like this:
| Susan | 35 | 10:60 |
| Peter | 33 | 10:40 |
| Jack | 32 | 10:50 |
| Jill | 31 | 10:20 |
| Peter | 31 | 10:30 |
1 Answer