1

我需要一些有关 MySQL 查询的帮助。我正在尝试使用 WHERE 子句对参与者进行排名。所以,我想分别对新手、中级和经验者进行排名。例如:

Rank Name    Grade  Type
----------------------------------
1    Bob     98     Novice 
2    Jill    88     Novice 
3    Jimmy   42     Novice 
1    Mark    87     Intermediate 
2    Scott   85     Intermediate
3    Jim     77     Intermediate 
1    Jane    90     Advanced 
2    John    89     Advanced 
3    Josh    87     Advanced

我试过了:

SET @rank=0;

(SELECT @rank:=@rank+1 AS rank, name, grade, type FROM myTable WHERE type='novice' ORDER BY grade DESC)
UNION ALL
(SELECT @rank:=@rank+1 AS rank, name, grade, type FROM myTable WHERE type='intermediate' ORDER BY grade DESC)
UNION ALL
(SELECT @rank:=@rank+1 AS rank, name, grade, type FROM myTable WHERE type='experienced' ORDER BY grade DESC)

我想我需要以某种方式重新设置排名。也许我还有另一个问题?

4

2 回答 2

1

采用:

SELECT t.name,
       t.grade,
       t.type,
       (SELECT COUNT(*)
          FROM YOUR_TABLE x
         WHERE x.type = t.type
           AND x.grade >= t.grade) AS rank
 FROM YOUR_TABLE t

要处理两个成绩列,请使用:

SELECT t.name,
       t.grade1,
       t.grade2,
       t.type,
       (SELECT COUNT(*)
          FROM YOUR_TABLE x
         WHERE x.type = t.type
           AND (x.grade1 + x.grade2) >= (t.grade1 + t.grade2)) AS rank
 FROM YOUR_TABLE t

我如何将新手和中级放在一起,将高级分别排列?

采用:

SELECT y.*,
       (SELECT COUNT(*)
          FROM (SELECT *, 
                       CASE t.type
                         WHEN 'Advanced' THEN t.type
                         ELSE 'Non-Advanced'
                       END AS group_type
                  FROM YOUR_TABLE) x
         WHERE x.group_type = y.group_type
           AND (x.grade1 + x.grade2) >= (y.grade1 + y.grade2)) AS rank
  FROM (SELECT t.name,
               t.grade1,
               t.grade2,
               t.type,
               CASE t.type
                 WHEN 'Advanced' THEN t.type
                 ELSE 'Non-Advanced'
               END AS group_type
          FROM YOUR_TABLE t) y
于 2010-08-03T16:04:57.923 回答
0

您可以使用更复杂的ORDER BY子句一次性完成。

SELECT @rank:=@rank+1 AS rank, name, grade, type 
FROM myTable 
ORDER BY 
    case type when 'novice'       then 1
              when 'intermediate' then 2 
              when 'experienced'  then 3 end,
    grade DESC
;

为了使它更好,您可以使用一个Type表来存储排序顺序,然后添加一个连接,然后简单地按 type.sort_order 排序,然后是等级,例如。

SELECT @rank:=@rank+1 AS rank, name, grade, type 
FROM myTable 
JOIN Types ON myTable.type = Types.type 
ORDER BY Types.sort_order, grade DESC;
于 2010-08-03T16:10:12.777 回答