提个问题,mysql下查询每个类别前2条记录

JerryBeckF 2009-12-09 05:46:04
id name type score
1 ming 中学生 50
2 wang 大学生 80
3 lilei 小学生 70
4 qiang 小学生 60
5 mimi 中学生 66
6 coco 大学生 55
7 alex 中学生 44
8 bruce 大学生 88
9 tom 小学生 91
......
想得出每个学生类型(type)下成绩(score)排前2条的记录
谢谢。。大概很难
...全文
190 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wwwwb 2009-12-10
  • 打赏
  • 举报
回复
同名如何处理
select a.name,a.type,a.score from tt a left join tt b
on a.type=b.type and a.score<=b.score group by a.name,a.type,a.score having count(b.score)<=2
ACMAIN_CHM 2009-12-09
  • 打赏
  • 举报
回复
mysql> select * from t_JerryBeckF;
+------+-------+--------+-------+
| id | name | type | score |
+------+-------+--------+-------+
| 1 | ming | 中学生 | 50 |
| 2 | wang | 大学生 | 80 |
| 3 | lilei | 小学生 | 70 |
| 4 | qiang | 小学生 | 60 |
| 5 | mimi | 中学生 | 66 |
| 6 | coco | 大学生 | 55 |
| 7 | alex | 中学生 | 44 |
| 8 | bruce | 大学生 | 88 |
| 9 | tom | 小学生 | 91 |
+------+-------+--------+-------+
9 rows in set (0.00 sec)

mysql> select *
-> from t_JerryBeckF a
-> where 2>(select count(*)
-> from t_JerryBeckF
-> where type=a.type
-> and score>a.score)
-> order by type,score desc;
+------+-------+--------+-------+
| id | name | type | score |
+------+-------+--------+-------+
| 9 | tom | 小学生 | 91 |
| 3 | lilei | 小学生 | 70 |
| 5 | mimi | 中学生 | 66 |
| 1 | ming | 中学生 | 50 |
| 8 | bruce | 大学生 | 88 |
| 2 | wang | 大学生 | 80 |
+------+-------+--------+-------+
6 rows in set (0.00 sec)

mysql>
ACMAIN_CHM 2009-12-09
  • 打赏
  • 举报
回复
select *
from yourTable a
where 2>(select count(*) from yourTable where type=a.type and score>a.score)

56,679

社区成员

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

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