从具有相应列值的多列mysql中选择最大值

时间:2019-11-18 09:56:09

标签: mysql

我在MySQL中具有以下结构的查询结果

 class | eng  | math | sci | ss  | kisw
-------+------------+-------------------
 4N    | 80.2 | 41.2 |96.3 |52.0 | 41.5
 4S    | 52.3 | 45.2 |98.5 |65.2 | 85.3
 5N    | 74.3 | 87.0 |69.9 |74.2 | 84.5
 5S    | 87.5 | 45.6 |72.3 |25.6 | 10.3

上面的查询给出了每个班级的学科分数。我想执行一个查询,该查询将为我提供每个学科最好的课程。最终结果应该是这样的:

subject | class | score
--------+-------+-------
eng     | 5S    | 87.5
math    | 5N    | 87.0
sci     | 4S    | 98.5
ss      | 5N    | 74.2
kisw    | 4S    | 85.3

我尝试着看这些问题,但是没有一个答案解决了为许多具有相应列值的列选择最大值的问题

Select MAX value from column and corresponding value from another

2 个答案:

答案 0 :(得分:1)

您可以尝试使用全部合并

select 'eng' as subject,class,eng from tablename 
where eng =(select max(eng) from tablename)
union all
select 'math',class,math from tablename 
where math=(select max(math) from tablename)
union all
select 'sci',class,sci from tablename 
where sci=(select max(sci) from tablename)
union all
select 'ss',class,ss from tablename 
where ss=(select max(ss) from tablename)
union all
select 'kisw', class,kisw from tablename 
where kisw=(select max(kisw) from tablename)

答案 1 :(得分:-1)

选择* 从(选择主题,班级,分数         从表) PIVOT(MAX(score)AS max_score FOR(subject)IN('eng'AS eng,'math'AS math,'sci'AS sci,'ss as ss,'kisw'as kisw));