0

如何对多列的行进行排序,以使排序保持这样的条件,即如果两个人具有相同的详细信息,他们将获得相同的排名。我将举一个例子来说明:这里首先按分数进行排序,如果平局有罚分,如果平局存在,则两者都被赋予相同的排名,下一个人获得调整后的排名。

###################
rank roll score penalty
 1    11    3     23
 2    12    3     20
 2    13    3     20
 2    14    3     20
 5    15    2     10

所以问题是如何填充排名列??如果在 mysql 中不可能,其他选择是什么?

4

2 回答 2

1

测试数据:

/*
drop table test;
create table test (roll int, score int, penalty int);
insert into test (roll, score, penalty) values (11, 3, 23), (12, 3, 20), (13, 3, 20), (14,3,20), (15, 2, 10);
*/

它来了:

ALTER TABLE test ADD COLUMN `rank` int FIRST;
CREATE TEMPORARY TABLE tmp_test LIKE test;
INSERT INTO tmp_test (`rank`, roll, score, penalty)
SELECT cast(q.`rank` as unsigned integer) as `rank`, roll, score, penalty FROM (
SELECT IF(@prev != CONCAT(sq.score, '_', sq.penalty), @rownum:=@rownum2, @rownum) AS rank, 
@prev:=CONCAT(sq.score, '_', sq.penalty), 
@rownum2:=@rownum2 + 1,
sq.*
FROM (
  SELECT
  roll, score, penalty
  FROM
  test
  , (SELECT @rownum:=0, @prev:='', @rownum2:=1) r 
  ORDER BY score DESC, penalty DESC
) sq
) q;

UPDATE test t INNER JOIN tmp_test tt ON t.roll = tt.roll AND t.score = tt.score AND t.penalty = tt.penalty
SET t.rank = tt.rank;
/*optionally...*/    
DROP TABLE tmp_test;

您需要在此处使用临时表,因为您无法更新正在读取的表。会话结束时将自动删除临时表。

于 2012-06-29T14:26:23.073 回答
0

尝试这个:

SET @row = 0; 
select min(a.Row) as Rank, s.Roll, s.Score, s.Penalty
from (
    select @row := @row + 1 AS Row, 
        Roll, 
        Score, 
        Penalty
    from Score
    order by Score desc, Penalty desc
) a
inner join Score s on a.Score = s.Score and a.Penalty = s.Penalty
group by Roll, Score, Penalty
order by min(Row)
于 2012-06-29T14:25:04.650 回答