Mysql 查詢實現成績排名,相同分數名次相同,類似於rank()函數
近日系統要實現總分成績排名,而且相同分數的學生排名要一樣,在網上搜了一圈,沒有找到合適的方法,只能靠自己實現了,這里提供兩種方法
//還有其他排名方式可以借鑒https://blog.csdn.net/a9925/article/details/76804951
1、sql查詢實現
測試如下:
mysql> select * from score ;
+----------+--------------+---------------------+--------------+-------+
| study_no | student_name | subject_id | subject_name | score | +----------+--------------+---------------------+--------------+-------+ | student1 | student1 | CodeCourseSubject_0 | 語文 | 120 | | student2 | student2 | CodeCourseSubject_0 | 語文 | 110 | | student3 | student3 | CodeCourseSubject_0 | 語文 | 110 | | student4 | student4 | CodeCourseSubject_0 | 語文 | 80 | | student5 | student5 | CodeCourseSubject_0 | 語文 | 81 | | student1 | student1 | CodeCourseSubject_2 | 英語 | 150 | | student2 | student2 | CodeCourseSubject_2 | 英語 | 130 | | student3 | student3 | CodeCourseSubject_2 | 英語 | 130 | | student4 | student4 | CodeCourseSubject_2 | 英語 | 44 | | student5 | student5 | CodeCourseSubject_2 | 英語 | 45 | +----------+--------------+---------------------+--------------+-------+ 10 rows in set
首先這里對科目顯示進行了行列轉換,並且對以學號study_no進行分組計算總分,並且按排名排序,
sql如下:
SELECT @rownum:=@rownum+1 AS rownum, if(@total=total,@rank,@rank:=@rownum)as rank, @total:=total, A.* FROM (SELECT study_no AS studyNo, student_name AS studentName, SUM(score) AS total, SUM(IF(subject_id='CodeCourseSubject_0',score,0)) AS 語文, SUM(IF(subject_id='CodeCourseSubject_2',score,0)) AS 英語 FROM score GROUP BY study_no ORDER BY total DESC )A,(SELECT @rank:=0,@rownum:=0,@total:=null)B
結果:
+--------+------+---------------+----------+-------------+-------+-------+-------+
| rownum | rank | @total:=total | studyNo | studentName | total | 語文 | 英語 | +--------+------+---------------+----------+-------------+-------+-------+-------+ | 1 | 1 | 270.0 | student1 | student1 | 270.0 | 120.0 | 150.0 | | 2 | 2 | 240.0 | student2 | student2 | 240.0 | 110.0 | 130.0 | | 3 | 2 | 240.0 | student3 | student3 | 240.0 | 110.0 | 130.0 | | 4 | 4 | 126.0 | student5 | student5 | 126.0 | 81.0 | 45.0 | | 5 | 5 | 124.0 | student4 | student4 | 124.0 | 80.0 | 44.0 | +--------+------+---------------+----------+-------------+-------+-------+-------+ 5 rows in set
可見排名第二名有兩個相同的分數,后面的排名自動往后移。
下面提供另外一種在程序中實現的方法:
2、程序實現
首先獲得全班總分並且以降序排序
public List<Object[]> findAllTotalScore() { String sql = "SELECT study_no,sum(score) AS total from score s "; javax.persistence.Query query = em.createNativeQuery(sql); return query.getResultList(); }
對獲得的總分信息進行排序和封裝成map(study_no,rank)
private Map<String, Long> rank(List<Object[]> objects) { long previousRank = 1; double total = 0; //記錄排名的map,map<study_no,排名> Map<String, Long> rankMap = new HashMap<>(); for (int i = 0; i < objects.size(); i++) { Object[] object = objects.get(i); //計算名次,相同分數排名一樣 if (total == (double) object[1]) { rankMap.put(object[0].toString(), previousRank); } else { rankMap.put(object[0].toString(), i + 1L); total = (double) object[1]; previousRank = i + 1; } } return rankMap; }
使用map直接根據學號就可以獲得成績排名。