通过交替性别(男/女)订购结果

时间:2013-09-26 18:10:54

标签: mysql

如何按性别(#1男性,#1女性,#2男性,#2女性)交替获得最佳分数来订购结果

| uid   | gender | name      | score |
|     1 |   male |    robert |    96 |
|     2 | female |     linda |    38 |
|     3 | female |      kate |    99 |
|     4 |   male |      jack |    76 |
|     5 | female |      nina |    33 |
|     6 |   male |    pierre |   126 |

所以我想要男性,女性,男性,女性“然后按分数排序。

你能帮助我吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

这要求您在排序前对每个性别的分数进行排名。这是一个使用MySQL用户定义变量在派生表子查询中动态生成排名数的技巧:

SELECT rank, gender, score, name
FROM (
  SELECT STRAIGHT_JOIN score, name, 
    @rank:=IF(@gender=gender,@rank+1,1) AS rank, @gender:=gender AS gender
  FROM (SELECT @gender:=NULL) AS _init 
  JOIN results
  ORDER BY gender, score DESC
) AS ranked_scores
ORDER BY rank ASC, gender DESC;

在MySQL 5.6.12上测试过。

输出:

+------+--------+-------+--------+
| rank | gender | score | name   |
+------+--------+-------+--------+
|    1 | male   |   126 | pierre |
|    1 | female |    99 | kate   |
|    2 | male   |    96 | robert |
|    2 | female |    38 | linda  |
|    3 | male   |    76 | jack   |
|    3 | female |    33 | nina   |
+------+--------+-------+--------+

以下是SQLFiddle的链接,显示上述查询有效。

重新评论:

如果您有任何错误,则需要更具体并分享错误消息。我无法猜出你看到了什么。

我不会回答有关按名称排序的问题。

答案 1 :(得分:0)

您要做的是创建两个临时数据集(在本例中为临时表),一个用于男性,一个用于女性。按分数排序。 然后遍历每个表,将每一行添加到结果集中。

SELECT *
FROM Table 
    INTO maleOnly
WHERE gender = 'male'
ORDER BY score

SELECT *
FROM Table 
    INTO femOnly
WHERE gender = 'female'
ORDER BY score


DECLARE scores_cursor CURSOR
    FOR SELECT * FROM maleOnly
    FOR SELECT * FROM femOnly
OPEN scores_cursor 
FETCH NEXT FROM scores_cursor;

有更好的方法可以做到这一点,例如WITH(CTE),但这会给你一个想法。