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.

有帮助吗?

解决方案

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

其他提示

select t1.student,score.subject,score.marks,
CONCAT ('(',score.marks,'/',cnt,')',' ', TRUNCATE(score.marks/cnt,2),'% ') as 'marks%' 
FROM 
(select count(subject) as cnt, student from score group by student) as t1
INNER JOIN score on t1.student=score.student;

+---------+---------+-------+----------------+
| student | subject | marks | marks%         |
+---------+---------+-------+----------------+
| A1      | phy     |    20 | (20/2) 10.00%  |
| A1      | bio     |    87 | (87/2) 43.50%  |
| A2      | che     |    24 | (24/1) 24.00%  |
| A3      | che     |    50 | (50/3) 16.66%  |
| A3      | phy     |    80 | (80/3) 26.66%  |
| A3      | maths   |    90 | (90/3) 30.00%  |
+---------+---------+-------+----------------+
6 rows in set (0.00 sec)

Sample Data:
mysql> select * from score;
+---------+---------+-------+
| student | subject | marks |
+---------+---------+-------+
| A1      | phy     |    20 |
| A1      | bio     |    87 |
| A2      | che     |    24 |
| A3      | che     |    50 |
| A3      | phy     |    80 |
| A3      | maths   |    90 |
+---------+---------+-------+
6 rows in set (0.00 sec)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top