2013-01-16 115 views
1

我有一個結果表所示:動態獲取排名由MySQL查詢

 

ID STUDENT_ID Branch_id Class_id Exam_id Subject_id Numbers  Date 
1  653   5   1   1 8    60  2012-01-01 
2  653   5   1   1 9    40  2012-01-01 
3  653   5   1   1 10    80  2012-01-01 
4  653   5   1   1 11    50  2012-01-01 
5  653   5   1   1 12    65  2012-01-01 
6  653   5   1   1 13    33  2012-01-01 
7  653   5   1   1 15    86  2012-01-01 
8  222   5   1   1 8    100  2012-01-01 
9  222   5   1   1 9    80  2012-01-01 
10  222   5   1   1 10    92  2012-01-01 
11  222   5   1   1 11    50  2012-01-01 
12  222   5   1   1 12    65  2012-01-01 
13  222   5   1   1 13    33  2012-01-01 
7  222   5   1   1 15    86  2012-01-01 

我的願望結果,如:

 

Student_ID Math English  Science Total Rank 
1  90 89  88 267 1 
2  90 89  88 267 1 
3  58 45  98 201  2 


我想用這種方法讓學生排名:

​​

SET @rank = 0, @prev_val = NULL; 

SELECT rank, correct FROM 
(
    SELECT 
     @rank := IF(@prev_val=correct,@rank,@rank+1) AS rank, 
     @prev_val := correct AS correct, uid 
    FROM quiz_user 
    ORDER BY correct DESC 
)as result WHERE uid=xxxxxxxxxxxx 

這個查詢我只需要區別表結構作者的帖子在正確的列上分配一個等級,我需要在總和所有數字之後在數字SUM(數字)列上指定等級。

請幫忙。

+0

請clearify你想要什麼你的問題? –

+0

如果一個或多個學生的成績相同,我想獲得學生的排名:兩名學生在500分中獲得500分,這意味着兩個學生都處於第一位。所以在上面的查詢工作正常,如果兩個是平等的只有我想計算排名上SUM(數字),而不是正確的列。 – Zia

+0

你能提供這個樣本數據的模式嗎? –

回答

1

試試這個:

SELECT STUDENT_ID, Numbers, IF(@marks=(@marks:=Numbers), @auto, @auto:[email protected]+1) rank 
FROM (SELECT STUDENT_ID, SUM(Numbers) Numbers 
     FROM quiz_user 
     GROUP BY STUDENT_ID 
     ORDER BY Numbers DESC, STUDENT_ID 
    ) AS A, (SELECT @auto:=0, @marks:=0) AS B; 
+0

我想問另一個問題?爲所有職級。 – Zia

+0

@Zia想問什麼?解釋我 –

+0

我使用數據透視查詢類如: SELECT MA_TH,(IF(subject_id = 1),sum(numbers)AS total,branch_id,depart_id,class_id,SUM(IF(subject_id = 1,numbers,0) 2,numbers,0))AS Eng, SUM(IF(subject_id = 3,numbers,0))AS URDU FROM marksheet where branch_id = 1 AND depart_id = 1 AND class_id = 1 GROUP BY stu_id ORDER BY total DESC 以excel格式顯示所有班級成績。我也可以在這個查詢中獲得排名嗎? – Zia