我想使用总数和某些条件(例如,exam_Id,class_id,section_id,年份)进行排名。我有许多数据使用不同的exam_Id,class_id,section_id,年份。现在,我想在这些项目(例如exam_Id,class_id,section_id,year)匹配时对它们进行排名。 在下面,我给了您一个sql查询,我尝试了一些方法,但是却给出了整个结果。
SELECT id, student_id, total_mark, FIND_IN_SET( total_mark, (
SELECT GROUP_CONCAT( total_mark
ORDER BY total_mark DESC )
FROM total_marks )
) AS rank
FROM total_marks
答案 0 :(得分:3)
如果要使用此方法对记录组进行排名,则需要相关的子查询:
SELECT id, student_id, exam_id, class_id, total_mark, section_id, year,
FIND_IN_SET(total_mark,
(SELECT GROUP_CONCAT( total_mark ORDER BY total_mark DESC )
FROM total_marks tm2
WHERE tm2.exam_Id = tm.exam_id AND
tm2.class_id = tm.class_id AND
tm2.section_id = tm.section_id AND
tm2.year = tm.year
)
) AS rank
FROM total_marks tm;
Here是db <>小提琴。
请注意,正确的编写方法是使用窗口函数:
SELECT tm.*,
RANK() OVER (PARTITION BY exam_Id, class_id, section_id, year
ORDER BY total_mark DESC
) as rank
FROM total_marks tm;
此功能是标准SQL,从8.0版开始在MYSQL中可用。