Calculating Percentage of Total in SQL
Submitted by madvip on Fri, 11/23/2007 - 10:20.
Suppose we have the following table which consists of two columns - a user and his favorite album.
mysql> select * from albums_votes; +-----------+----------+ | user | album_id | +-----------+----------+ | 1000 | 2 | | 2000 | 3 | | 3000 | 1 | | 4000 | 3 | | 5000 | 3 | | 6000 | 3 | | 531514255 | 1 | | 686711159 | 2 | | 618496371 | 2 | | 705891065 | 2 | +-----------+----------+ 10 rows in set (0.00 sec)
If we wanted to know how much each album was voted, we would do the following query:
mysql> select album_id, count(*) from albums_votes group by album_id order by count(album_id) desc; +----------+----------+ | album_id | count(*) | +----------+----------+ | 2 | 4 | | 3 | 4 | | 1 | 2 | +----------+----------+ 3 rows in set (0.00 sec)
To represent the vote count as a percentile value of the total casted votes, we can use the following query:
mysql> select a.album_id, count(*), t.total, count(*) / t.total * 100 from albums_votes a, ( select count(*) as total from albums_votes ) t group by a.album_id order by count(*) desc;
+----------+----------+-------+--------------------------+ | album_id | count(*) | total | count(*) / t.total * 100 | +----------+----------+-------+--------------------------+ | 2 | 4 | 10 | 40.0000 | | 3 | 4 | 10 | 40.0000 | | 1 | 2 | 10 | 20.0000 | +----------+----------+-------+--------------------------+ 3 rows in set (0.00 sec)

