Home > Database > Mysql Tutorial > body text

MySQL实现ORALCE的row_number()over(partition by xx)功能_MySQL

WBOY
Release: 2016-06-01 13:07:59
Original
1277 people have browsed it

比如有个需求,要找出班级里每门课分数最高的学生(课程名称,分数,学生姓名),注意这里不是只取最高分,要把课程名称,分数,学生姓名都取出来!

在ORALCE里我们可以用ROW_NUMBER()OVER轻松实现,但是在mysql里就有点麻烦了,不过还是可以做的。

select course,score,name

from

(select

heyf_tmp.course,
heyf_tmp.score,
heyf_tmp.name,
@rownum:=@rownum+1,
if(@pdept=heyf_tmp.course,@rank:=@rank+1,@rank:=1) as rank,          -- 分组字段
@pdept:=heyf_tmp.course
from 
(select course,name,score
from temp_student_score
order by course,score desc                                           -- 分组字段,排序字段
) heyf_tmp ,

(select @rownum :=0,@pdept := null ,@rank:=0) a 

) a where rank=1

最后我们只用取出RANK=1的部分就可以了

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!