我有一个类似
的表结构+------+---------+-------+
| 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) |
+----------+----------------+------------+-----------------+
有办法吗?
请帮忙。
答案 0 :(得分: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
答案 1 :(得分: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)