[英]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.