mysql>
mysql> CREATE TABLE testscore
-> (
-> subject INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> age INT UNSIGNED NOT NULL,
-> sex ENUM('M','F') NOT NULL,
-> score INT,
-> PRIMARY KEY (subject)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> INSERT INTO testscore (age,sex,score)
-> VALUES
-> (5,'M',5),
-> (5,'M',4),
-> (5,'F',6),
-> (5,'F',7),
-> (6,'M',8),
-> (6,'M',9),
-> (6,'F',4),
-> (6,'F',6),
-> (7,'M',8),
-> (7,'M',6),
-> (7,'F',9),
-> (7,'F',7),
-> (8,'M',9),
-> (8,'M',6),
-> (8,'F',7),
-> (8,'F',10),
-> (9,'M',9),
-> (9,'M',7),
-> (9,'F',10),
-> (9,'F',9)
-> ;
Query OK, 20 rows affected (0.00 sec)
Records: 20 Duplicates: 0 Warnings: 0
mysql>
mysql>
mysql> CREATE TABLE ref (score INT);
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO ref (score)
-> VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
Query OK, 11 rows affected (0.00 sec)
Records: 11 Duplicates: 0 Warnings: 0
mysql>
mysql> SELECT subject, age, sex, score FROM testscore ORDER BY subject;
+---------+-----+-----+-------+
| subject | age | sex | score |
+---------+-----+-----+-------+
| 1 | 5 | M | 5 |
| 2 | 5 | M | 4 |
| 3 | 5 | F | 6 |
| 4 | 5 | F | 7 |
| 5 | 6 | M | 8 |
| 6 | 6 | M | 9 |
| 7 | 6 | F | 4 |
| 8 | 6 | F | 6 |
| 9 | 7 | M | 8 |
| 10 | 7 | M | 6 |
| 11 | 7 | F | 9 |
| 12 | 7 | F | 7 |
| 13 | 8 | M | 9 |
| 14 | 8 | M | 6 |
| 15 | 8 | F | 7 |
| 16 | 8 | F | 10 |
| 17 | 9 | M | 9 |
| 18 | 9 | M | 7 |
| 19 | 9 | F | 10 |
| 20 | 9 | F | 9 |
+---------+-----+-----+-------+
20 rows in set (0.00 sec)
mysql>
mysql> SELECT @n := COUNT(score) FROM testscore;
+--------------------+
| @n := COUNT(score) |
+--------------------+
| 20 |
+--------------------+
1 row in set (0.00 sec)
mysql>
mysql> SELECT ref.score, (COUNT(testscore.score)*100)/@n AS percent
-> FROM ref LEFT JOIN testscore ON ref.score = testscore.score
-> GROUP BY ref.score;
+-------+---------+
| score | percent |
+-------+---------+
| 0 | 0.0000 |
| 1 | 0.0000 |
| 2 | 0.0000 |
| 3 | 0.0000 |
| 4 | 10.0000 |
| 5 | 5.0000 |
| 6 | 20.0000 |
| 7 | 20.0000 |
| 8 | 10.0000 |
| 9 | 25.0000 |
| 10 | 10.0000 |
+-------+---------+
11 rows in set (0.00 sec)
mysql>
mysql> drop table testscore;
Query OK, 0 rows affected (0.00 sec)
mysql> drop table ref;
Query OK, 0 rows affected (0.00 sec)