查询每类最大的两个值的SQL要怎么写啊~~

afeiqiang 2012-06-01 10:39:44
比如这样的场景:表 exam 记录学生每次测验的成绩,stu_id 是学生id,score 是成绩。查询出全部学生的最好的两次测验成绩的sql要怎么写?
比如表 exam 的数据如下,

1 98
1 96
2 100
1 85
2 89
2 90
3 82
3 66
3 75

查询到结果应该是
1 98
1 96
2 100
2 90
3 82
3 75
...全文
222 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
afeiqiang 2012-06-04
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]

select *
from exam a
where id in (select id from exam where ClsNo=a.ClsNo order by Score desc limit 2)
order by a.ClsNo,a.Score desc
[/Quote]

上面几条亲测全通不过,不过还是谢谢
afeiqiang 2012-06-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

参考下贴中的多种方法

http://blog.csdn.net/acmain_chm/article/details/4126306
[征集]分组取最大N条记录方法征集,及散分....
[/Quote]

这个很好,谢谢
afeiqiang 2012-06-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
SELECT * from tty a where 2>(select count(*) from tty where a.id=id and a.score<score)
[/Quote]
琢磨了很久,终于弄明白了
Rotel-刘志东 2012-06-01
  • 打赏
  • 举报
回复
select *
from exam a
where id in (select id from exam where ClsNo=a.ClsNo order by Score desc limit 2)
order by a.ClsNo,a.Score desc

Rotel-刘志东 2012-06-01
  • 打赏
  • 举报
回复
select *
from Table1 a
where id in (select id from Table1 where ClsNo=a.ClsNo order by Score desc limit 2)
order by a.ClsNo,a.Score desc

ACMAIN_CHM 2012-06-01
  • 打赏
  • 举报
回复
参考下贴中的多种方法

http://blog.csdn.net/acmain_chm/article/details/4126306
[征集]分组取最大N条记录方法征集,及散分....
Rotel-刘志东 2012-06-01
  • 打赏
  • 举报
回复
select id, max(score) from exam
group by id
having count(id)=2
limit 2;
wwwwb 2012-06-01
  • 打赏
  • 举报
回复



SELECT * from tty a where 2>(select count(*) from tty where a.id=id and a.score<score)
小小小小蜗牛 2012-06-01
  • 打赏
  • 举报
回复
不来这么复杂啦 会晕的
select id, max(score) from exam
group by id
having count(id)=2
limit 2; 这个不错

56,679

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧