select a.class, a.student_name, a.score from test.student_scores a where ( selectcount(*) from test.student_scores b where a.class = b.class and a.score < b.score ) <10 orderby a.class, score desc;
求每个班中分数最高的学生
利用子查询:
1 2 3 4 5 6 7 8
select a.class, a.student_name, a.score from test.student_scores a where ( selectcount(*) from test.student_scores b where a.class = b.class and a.score < b.score ) <1 orderby a.class, score desc;
也是利用子查询
1 2 3 4 5 6 7 8
select a.class, a.student_name, a.score from test.student_scores a where a.score = ( selectmax(score) from test.student_scores b where a.class = b.class )
利用join
1 2 3 4 5 6 7
select a.class, a.student_name, a.score from test.student_scores a innerjoin ( select class, max(score) as max_score from test.student_scores groupby class ) b on a.class = b.class and a.score = b.max_score
select s.name, s.score from students s leftjoin score sc1 on s.sid = sc1.sid and sc1.cid =1 leftjoin score sc2 on s.sid = sc2.sid and sc2.cid =2 where sc1.cid isnulland sc2.cid isnotnull;
学生成绩表(sid,cid,score)查询总分排名在5-10名的学生id及对应的总分
rank() 是窗口函数,order by 子句在 over 子句中用于指定如何对窗口内的结果集进行排序
1 2 3 4 5 6 7 8 9 10 11 12 13
WITH StudentTotalScore as ( select sid, sum(socre) as totalScore from scores groupby sid ), StudentRank as( select sid, totalScore, RANK() over (orderby totalScore desc) as ranking from StudentTotalScore ), select sid, totalScore from StudentRank where ranking between5and10