成績表內有多人多科目的成績,查詢平均成績前百分之二十的同學

成績表內有多人多科目的成績,查詢平均成績前百分之二十的同學

故意把學生id和score id數據不連續。

第一種:

成績表內有多人多科目的成績,查詢平均成績前百分之二十的同學

第二種:

成績表內有多人多科目的成績,查詢平均成績前百分之二十的同學

第一種:

select result1.* from 
\t(select student_id, avg(score) as avgScore from subject_score group by student_id order by avgScore desc) result1
where (select count(*) from (select student_id, avg(score) as avgScore from subject_score group by student_id) result2) * 0.2
> (select count(*) from (select student_id, avg(score) as avgScore from subject_score group by student_id) result3 where result1.avgScore < result3.avgScore)

第二種:

select view2.* from (
\tselect view1.*, (@i:=@i+1) as rownum from (
\t\tselect student_id, avg(score) as avgScore from subject_score
\t\tgroup by student_id order by avgScore desc
\t) as view1,
\t(select @i:=0) as init
) as view2
where view2.rownum <= (@i * 0.2);

第二種:需要先排序,再加一次嵌套查詢加上行號,因為select中的語句先於order by執行,如果不二次查詢,打上的行號可能是錯誤的(先加行號再排序)。


分享到:


相關文章: