找到具有主题名称的每个学生的最高分数

时间:2017-08-26 06:04:19

标签: sql

studentid   maths   science art computer sports
1             55     68      59   75     62
2             75     68      79   56     89
3             89     85      74   32     56
4             89     92      86   75     12
5             99     100     45  68      45

如何获得这样的查询结果

studentid   maths   science art computer sports

1                                   75  
2                                           89
3             89     
4                     92        
5                     100    

并且喜欢这个

studentid   MaxScore

1
2                                         
3            
4                      
5   

1 个答案:

答案 0 :(得分:2)

案例1

SELECT studentid, 
       CASE GREATEST(maths,science,art,computer,sports) 
         WHEN maths THEN math
         ELSE ''
       END AS math,
CASE GREATEST(maths,science,art,computer,sports) 
         WHEN science THEN science
         ELSE ''
       END AS science,
CASE GREATEST(maths,science,art,computer,sports) 
         WHEN art THEN art
         ELSE ''
       END AS art,
CASE GREATEST(maths,science,art,computer,sports) 
         WHEN computer THEN computer
         ELSE ''
       END AS computer,
CASE GREATEST(maths,science,art,computer,sports) 
         WHEN sports THEN sports
         ELSE ''
       END AS sports

FROM table_name

案例2

SELECT studentid, GREATEST(maths,science,art,computer,sports) as MaxScore
FROM table_name

在此处了解GREATEST() oracle docMysql