Search code examples
mysqloracle-databasemysql-workbenchmysql-error-1064

mysql query for calculating the percentage


I have a table structure like

+------+---------+-------+
| Name | Subject | Marks |
+------+---------+-------+
| A1   | phy     | 20    |
| A1   | bio     | 87    |
| A1   | mat     | 34    |
| A2   | che     | 56    |
| A3   | bio     | 62    |
| A3   | phy     | 87    |
| A3   | mat     | 75    |
+------+---------+-------+  

here I want to write mysql query to achieve the output of the above table should look like the below table

+----------+----------------+------------+-----------------+
|  Name    |      Subject   |  Marks     |     marks(%)    |
+----------+----------------+------------+-----------------+
| A1       |      phy       |    20      |   (20/3) 6.66%  |
|          |      bio       |    87      |   (87/3)        |
|          |     mat        |    34      |    (34/3)       |
| A2       |      che       |     56     |     (56/1)      |
| A3       |      bio       |      62    |     (62/2)      |
|          |     phy        |      87    |     (87/2)      |
+----------+----------------+------------+-----------------+

Is there a way to do this??

Please help.


Solution

  • Here's the MySQL solution. I think the main difference in Oracle will be the syntax for concatenating all the pieces of the marks(%) column.

    SELECT a.Name, a.Subject, a.Marks, 
           CONCAT('(', a.Marks, '/', b.cnt, ') ', TRUNCATE(a.Marks/b.cnt, 2), '%') AS 'marks(%)'
    FROM YourTable AS a
    JOIN (SELECT Name, COUNT(*) cnt
          FROM YourTable
          GROUP BY Name) AS b
    ON a.Name = b.Name
    ORDER BY Name
    

    DEMO