select a.sno,a.course,a.score from ( select course,score,row_number() over(partitionby course orderby score desc) as rn from lesson )a where a.rn<=2;
row_number() over(partition by course order by score desc)为hive中的函数
意思是以课程分组,按成绩递减排序,并为每组中的数据打上行号的标记,从1开始。
在MySQL中查询:
1 2 3 4 5 6 7 8 9
select sno,course,score from lesson a where3 > ( selectcount(1) from lesson b where a.score<b.score and a.course=b.course ) orderby a.course,a.score desc ;
这种只适合没有重复值的情况,当score有重复值的时候,查询结果是不正确的
优化:使用动态sql进行查询
1 2 3 4 5 6 7 8 9
SET @row=0; SET @groupid=''; select a.course,a.score from ( select sno,course,score,casewhen @groupid=course then @row:=@row+1else @row:=1endrownum,@groupid:=course from lesson orderby course,score desc )a where a.rownum<=5;