Search code examples
mysqlsqlsubquerycorrelated-subquery

Calculate percentage in mySQL where SUM is already present in the table


I have a table(Which I have no control over) like this:

enter image description here

As, you can see this already has total calculate in a separate row I have to do calculate percentage which should look something like this:

enter image description here

The issue is how do I pass Total in a sub query like SELECT Marks from <TABLE> WHERE Topic = 'Total';

, so that I only get a single row?

Thanks


Solution

  • You can do something along the lines of

    SELECT m1.*, ROUND(m1.marks / m2.marks * 100, 2) percentage
      FROM marks m1 join marks m2
        ON m1.name = m2.name AND m2.topic = 'Total'
     ORDER BY name, topic
    

    Output:

    | Name |   Topic | Marks | percentage |
    |------|---------|-------|------------|
    |  Joe |    Chem |    43 |      26.38 |
    |  Joe |   Maths |    75 |      46.01 |
    |  Joe | Physics |    45 |      27.61 |
    |  Joe |   Total |   163 |        100 |
    ...
    

    SQLFiddle