[英]Am having issues in grouping and rank in php
Am issues with grouping and rank in php i don;t know if my entire code is wrong but have been able to group it and rank but the ranking is not correct Here is my code 是在php中对分组和排名进行排序的问题;我不知道我的整个代码是否错误,但是已经能够对它进行分组和排名,但是排名不正确,这是我的代码
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
Here is the result 这是结果
regnumber subject_id score Rank
0217 11 89 1
0200 11 78 2
2021 11 50 3
7737 11 200 4
0917 11 100 5
Which is not correct 哪个不正确
Don't mind my code, all i need is a sql code that can group and rank also using where clause. 不用管我的代码,我所需要的只是一个可以使用where子句进行分组和排名的sql代码。 Thanks.
谢谢。
Your problem would appear to be storing the score as a string rather than a number. 您的问题似乎是将分数存储为字符串而不是数字。 You can fix the query.
您可以修复查询。 But I would go to the root cause and fix the problem by doing:
但我会找出根本原因并通过执行以下操作解决问题:
alter table modify column score int;
I do think the query is a bit cumbersome. 我确实认为查询有点麻烦。 I would be more inclined to write it using a correlated subquery or using variables.
我会更倾向于使用相关子查询或变量来编写它。 The latter is pretty simple:
后者非常简单:
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;
Note: This assumes that the type of score
is fixed. 注意:这是假设
score
类型是固定的。 It is easy enough to adjust the query by doing: 通过执行以下操作即可轻松调整查询:
ORDER BY (tr.score + 0) DESC, tr.regnumber DESC
seems that your score is a string 看来你的分数是一个字符串
in this case if you don't want change the struct of your table you can try cast your score column from string to 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.