这是我的数据集和当前代码:http://sqlfiddle.com/#!2/f9a605/3
| id | courseid | username | day | score |
--------------------------------------------
| 1 | 2 | tim | may 5 | 85 |
| 2 | 2 | mike | may 6 | 86 |
| 3 | 2 | tim | may 7 | 82 |
| 4 | 3 | tim | may 8 | 80 |
| 5 | 2 | mike | may 9 | 79 |
| 6 | 2 | joe | may 10| 81 |
我想为每个用户的最低分数选择值,其中courseid = 2按最低分数排序,因此结果应如下所示:
| mike | may 9 | 79 |
| joe | may 10 | 81 |
| tim | may 8 | 82 |
我目前的代码如下:
SELECT courseid, username, day, MIN(score) FROM result where courseid = '2' GROUP BY username order by MIN(score) limit 10
我目前的结果如下:
| mike | may 6 | 79 |
| joe | may 10 | 81 |
| tim | may 5 | 82 |
日子不对。
当courseid = 2时,如何获得与该人的最低分数相对应的正确日期?
答案 0 :(得分:1)
这可以使用2个条件的自联接来完成,一个是用户名,另一个是最低分
SELECT r.courseid, r.username, r.`day`,r.score
FROM result r
JOIN (SELECT username, MIN(score) score
FROM result
where courseid = '2'
GROUP BY username) r1
ON(r.username = r1.username and r.score = r1.score)
order by r.score
limit 10
同样在您的预期结果中,蒂姆应该具有may7的日期
Fiddle Demo
答案 1 :(得分:0)
您可以使用子查询:
select courseid, username, day, score
from result x
where score = (select min(y.score)
from result y
where y.username = x.username
and x.courseid = y.courseid)
and courseid = 2
order by score
<强>小提琴:强>