[英]select max from multiple columns mysql with corresponding column value
我在 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
上面的查询给出了每个类的科目分数。 我想执行一个查询,该查询将为我提供每个主题的最佳 class。 最终结果应该是这样的:
subject | class | score
--------+-------+-------
eng | 5S | 87.5
math | 5N | 87.0
sci | 4S | 98.5
ss | 5N | 74.2
kisw | 4S | 85.3
我已经尝试查看这些问题,但没有一个答案解决了为具有相应列值的许多列选择最大值的问题
您可以尝试使用 union all
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)
SELECT * FROM (SELECT subject, class, score FROM TABLE ) PIVOT (MAX(score) AS max_score FOR (subject) IN ('eng' AS eng, 'math' AS math, 'sci' AS sci, 'ss' as ss , 'kisw' 作为 kisw));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.