Use of Variables
mysql>
mysql> CREATE TABLE mytable (
-> id int(11) NOT NULL default '0',
-> choice tinyint(4) NOT NULL default '0',
-> ts timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
-> PRIMARY KEY (id)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> INSERT INTO mytable VALUES (1,4,'2003-01-14 15:46:18'),
-> (2,1,'2003-01-14 15:49:44'),
-> (3,4,'2003-01-14 15:49:50'),
-> (4,4,'2003-01-14 15:49:53'),
-> (5,4,'2003-01-14 15:49:54'),
-> (6,2,'2003-01-14 15:49:58');
Query OK, 6 rows affected (0.00 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql>
mysql>
mysql>
mysql>
mysql> SELECT @total := COUNT(*) FROM mytable;
+--------------------+
| @total := COUNT(*) |
+--------------------+
| 6 |
+--------------------+
1 row in set (0.00 sec)
mysql>
mysql> SELECT choice, COUNT(*) / @total * 100 AS percentage FROM mytable GROUP BY choice ORDER BY percentage DESC;
+--------+------------+
| choice | percentage |
+--------+------------+
| 4 | 66.6667 |
| 1 | 16.6667 |
| 2 | 16.6667 |
+--------+------------+
3 rows in set (0.00 sec)
mysql>
mysql> drop table mytable;
Query OK, 0 rows affected (0.00 sec)
mysql>
Related examples in the same category