sql分組求和取最大值

問題:表t有三個字段,student(學生姓名),class(科目),score(成績),須要找到總成績最高的學生的姓名 (可能有多個) 一開始的作法: select student,sum(score) from t group by student having sum(score) = (select temp.s from (select student,sum(score) s from t group by student order by s desc limit 1) as temp) 思路是先分組求和,而後對和最大的值取出來,當分組求和的列表的一個值等於最大的值,則取出這條記錄。可是group by了兩次,想當不爽。 後面找到了rank函數,因而有了這個寫法 select * from ( with tmp as( select student,sum(score) as sum_score from student group by student ) select rank() OVER ( order by tmp.sum_score desc) as cc,* from tmp) as tc  where tc.cc = 1 把分組求和作成一個臨時視圖tmp,而後找出臨時視圖rank over排序後的排序爲1的記錄。 rank over函數在pg,mssql,oracle中均可用,在mysql中不能用
相關文章
相關標籤/搜索