在php中分组和排名的问题我不知道我的整个代码是否错误但是能够对它进行分组和排名但是排名不正确 这是我的代码
parent_id
结果如下
SELECT g1.regnumber, g1.subject_id , g1.score , COUNT(*) AS rank
FROM tbl_result AS g1 JOIN
tbl_result AS g2
ON (g2.score, g2.regnumber) >= (g1.score, g1.regnumber) AND
g1.subject_id = g2.subject_id
WHERE g2.subject_id='11'
GROUP BY g1.regnumber, g1.subject_id , g1.score
ORDER BY g1.subject_id , rank
哪个不正确
不要介意我的代码,我需要的只是一个sql代码,可以使用where子句进行分组和排名。 感谢。
答案 0 :(得分:0)
您的问题似乎是将分数存储为字符串而不是数字。您可以修复查询。但我会找到根本原因并通过以下方式解决问题:
alter table modify column score int;
我确实认为查询有点麻烦。我更倾向于使用相关子查询或使用变量来编写它。后者非常简单:
SELECT tr.regnumber, tr.subject_id, tr.score,
(@rn := @rn + 1) as rank
FROM (SELECT tr.*,
FROM tbl_result tr
WHERE g1.adnumber = 'ctydemo' AND g2.subject_id = 11
ORDER BY tr.score DESC, tr.regnumber DESC
) tr CROSS JOIN
(SELECT @rn := 0) params
ORDER BY tr.subject_id, rank;
注意:这假定score
的类型是固定的。通过执行以下操作来调整查询很容易:
ORDER BY (tr.score + 0) DESC, tr.regnumber DESC
答案 1 :(得分:0)
似乎你的分数是一个字符串
在这种情况下,如果您不想更改表格的结构,可以尝试将得分列从字符串转换为int
SELECT g1.regnumber, g1.subject_id , g1.score , COUNT(*) AS rank
FROM tbl_result AS g1 JOIN
tbl_result AS g2
ON (cast(g2.score as integer), g2.regnumber) >= (cast(g1.score as integer), g1.regnumber) AND
g1.subject_id = g2.subject_id
WHERE g2.subject_id='11'
GROUP BY g1.regnumber, g1.subject_id , g1.score
ORDER BY g1.subject_id , rank