How can I find the ratio?

Hi,

I’m building a tag cloud and since it’s for a large site I’m saving the counts in a table to avoid counting everything with each request, here it is:

CREATE TABLE `counts` (
  `name` char(35) NOT NULL DEFAULT '',
  `total` int(11) NOT NULL,
  `type` tinyint(4) NOT NULL,
  `locale_id` smallint(6) NOT NULL,
  PRIMARY KEY (`name`,`type`,`locale_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `counts` (`name`, `total`, `type`, `locale_id`)
VALUES
 	('k3k3k',888,3,1),
	('krkrkrkr',333,3,1),
	('zzxzx',22,3,1);

name is the tag word and total is how many times it is mentioned in the tag table. I need to get the percentage of every tag to build the tag cloud.

How can I do that?

Thanks.

You need the total count to calculate the ratio. Something like:


SELECT
    c.name
  , c.total
  , CASE WHEN t.total = 0 THEN 0
         ELSE c.total / t.total
    END AS ratio
FROM
  (SELECT SUM(total) AS total
   FROM counts
  ) AS t
CROSS JOIN counts AS c