使用Group_Concat和SUM进行Mysql排名

时间:2015-03-10 12:21:32

标签: php mysql sql

感谢大家提出的问题。

我找到了group_concat的解决方案。查询:

SELECT nisn,sum(nilai_angka) 

( select find_in_set( sum(nilai_angka),
( select
group_concat(distinct sum(nilai_angka)
order by sum(nilai_angka) DESC separator ',')
from nilai))
) as rangking

FROM nilai  
 group by nisn

但是我遇到了问题,因为find_in_set和group_concat无法接收SUM。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

对不起,我真的可以理解数据库中字段的名称,但是这里是我上一次面试的其中一个任务的一个小贴士,与你提出的要求非常相似。

SELECT
CONCAT(pF," ",pI," ",pO) AS pupil, 
#concat last,first and middle name of the student

@curRank := IF(@prevVal=score, @curRank, @curRank:= @curRank + 1 ) AS rank,
#compare scores to previous student to split places in case of equal results

@prevVal:=score as score
#save current score to compare with next student

FROM 
(SELECT @curRank := 0, @prevVal:=null) r, 
#trick to init variables without second query
tbl_results
#Fields: puppil_id, subject_id, score

LEFT JOIN tbl_pupils ON tbl_results.pupil_id=tbl_pupils.pidx
#Fields: pidx, pF, pI, pO

WHERE subject_id=2
ORDER BY score DESC;

这里的诀窍是在SELECT @curRank:=语句之后计算ORDER BY,这使得它非常容易。 这是一个互动版本:http://sqlfiddle.com/#!2/fee20/15 但现在似乎已经失败了。