2014-03-04 151 views
-3

我有一个像MySQL查询计算百分比

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

这里我想写MySQL查询实现上述表的输出应该看起来像下面的表

+----------+----------------+------------+-----------------+ 
| 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)  | 
+----------+----------------+------------+-----------------+ 

表结构有没有办法做到这一点??

请帮忙。

+1

你使用MySQL或Oracle?他们是两个非常不同的数据库。请适当地标记你的问题。 –

+0

为什么你的示例输出中没有'A3 mat'? – Barmar

回答

0

下面是MySQL解决方案。我认为Oracle的主要区别在于连接所有marks(%)列的语法。

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

+0

谢谢Barmar其作品对我来说很好:) – user3380194

0
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)