查询使用mysql中的条件查找排名

时间:2014-07-12 06:37:09

标签: mysql

我在表格中有这样的数据:

======================================= 
class |  name  |  study  |  avg scores
======================================= 
1      alfa       c#          75
1      alfa       php         70
1      beta       c#          80
1      beta       php         90
2      carlie     c#          70
2      carlie     php         70
2      delta      c#          90
2      delta      php         90

我想要这样的结果:

========================================== 
rangking |   class    |   name   | average
========================================== 
1             1           beta       85
2             1           alfa       72.5
1             2           delta      90
2             2           carlie     70

标准rangking 1 =平均值> 80

标准rangking 2 =平均值> 65和< 80

那么如何在mysql中进行查询以获得这些结果呢?

请帮助我,我已多次尝试但未成功

由于

2 个答案:

答案 0 :(得分:0)

SELECT CASE WHEN average > 80 THEN 1
            WHEN average > 65 THEN 2
       END AS rangking,
       class, name, average
FROM (SELECT class, name, AVG(avg_scores) AS average
      FROM YourTable
      GROUP BY class, name
      HAVING average > 65) AS subquery
ORDER BY class, rangking

答案 1 :(得分:0)

试试这个

SELECT CASE
           WHEN avg(average) >80 THEN 1
           WHEN avg(average)>65
                AND avg(average)<80 THEN 2
       END AS `ranking`,
       CLASS, name, avg(average) AS average
FROM TABLE_NAME
GROUP BY CLASS, name;