SQL分组求每组最大值问题的解决方法收集
(2011-02-10 13:06:13)
标签:
杂谈 |
例如有一个表student,其结构如下:
id
1
2
3
4
5
6
要求查询的结果如下:
id
3
2
4
6
顺序可调换,即为每个科目的最高分信息。
SQL如下:
法一:
select student.id,student.name,student.sort,student.score from student inner join (select sort, max(score) as score from student group by sort) B on student.sort=B.sort AND student.score=B.score order by id
法二:
select * from student a where not exists(select * from student where a.score<score and a.sort=sort )
法三:
select * from student a where 1〉(select count(*) from student where a.score<score and a.sort=sort )