0

I have a query result in MySQL with the following structure

 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

The above query gives subject scores for each of the classes. I want to perform a query that will give me the best class per subject. This is what the end result should look like :

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

I have tried looking at these questions but none of the answers addresses the issue of selecting a maximum value for many columns with a corresponding column value

Select MAX value from column and corresponding value from another

Benson Kiprono
  • 129
  • 1
  • 1
  • 12

2 Answers2

1

You can try using 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)
Fahmi
  • 37,315
  • 5
  • 22
  • 31
-1

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' as kisw));