我怎样才能找到这个比例?

时间:2012-01-07 09:28:35

标签: mysql sql

我正在建立一个标签云,因为它是针对一个大型网站我将表中的计数保存起来以避免计算每个请求的所有内容,这里是:

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是标记词,totaltag表中提及的次数。我需要获得每个标签的百分比来构建标签云。

我该怎么做?

3 个答案:

答案 0 :(得分:3)

   select 
     name, 
     total,
     total/(select sum(total) from counts)*100 as percentage
   from counts

答案 1 :(得分:2)

这样的事情应该这样做:

SELECT name,(total/(SELECT SUM(total) FROM counts)) * 100 
FROM counts WHERE name = 'k3k3k' 

我想要对结果进行舍入或进行其他格式化...

答案 2 :(得分:1)

规范化!也就是说,选择最大计数并将所有其他计数作为基础。

SELECT name, (total / @max_count * 100) percentage
FROM counts, (SELECT @max_count := MAX(total) FROM counts) t1;

结果:

+----------+------------+
| name     | percentage |
+----------+------------+
| k3k3k    |   100.0000 |
| krkrkrkr |    37.5000 |
| zzxzx    |     2.4775 |
+----------+------------+

或者您可以使用SUM代替MAX

SELECT name, (total / @max_count * 100) percentage
FROM counts, (SELECT @max_count := SUM(total) FROM counts) t1;


+----------+------------+
| name     | percentage |
+----------+------------+
| k3k3k    |    71.4401 |
| krkrkrkr |    26.7900 |
| zzxzx    |     1.7699 |
+----------+------------+