获取mysql 2中某个值的出现百分比

时间:2014-03-23 19:34:02

标签: mysql

this question之外,我还要尊重另一栏“post_id”:

ID | name | version | post_id
=============================
 1 | foo  | 1.0     |  2
 2 | bar  | 1.0     |  2
 3 | loo  | 1.1     |  1
 4 | zoo  | 1.2     |  2

输出现在应该是:

version | percentage | post_id
===============================
 1.0    | 0.667      | 2
 1.1    | 1.000      | 1
 1.2    | 0.333      | 2

The solution by Gordon Linoff工作得非常好,除了它计算所有条目的百分比(显然):

SELECT version, 
       Count(*) / const.cnt 
FROM   mytable 
       CROSS JOIN (SELECT Count(*) AS cnt 
                   FROM   mytable) const 
GROUP  BY version 
ORDER  BY version;

编辑(这不是我想要的!)

只将post_id添加到select中不会带来预期的结果:

SELECT version, 
       Count(*) / const.cnt,
       post_id
FROM   mytable 
       ....

输出为

version | percentage | post_id
===============================
 1.0    | 0.500      | 2
 1.1    | 0.250      | 1
 1.2    | 0.250      | 2

编辑以下是第一个想法的小提琴:http://sqlfiddle.com/#!2/f738d/1

3 个答案:

答案 0 :(得分:2)

认为这样做: -

SELECT version, 
       Count(*) / const.cnt ,
       mytable.post_id
FROM   mytable 
INNER JOIN (SELECT post_id, Count(*) AS cnt 
           FROM   mytable
           GROUP BY post_id) const 
ON mytable.post_id = const.post_id
GROUP  BY version, post_id
ORDER  BY version;

子查询获取每个帖子ID的记录数,然后使用此计数来计算此版本的分数。

答案 1 :(得分:0)

如果我理解您要将post_id添加到您选择的列中的问题,

   SELECT version, 
          Count(*) / const.cnt,
          post_id
   -- snip ---

答案 2 :(得分:0)

我有一个很好的,功能齐全的解决方案,它涉及mysql和你的脚本语言,并循环遍历表:

首先查询每个post_id值并将其分配给变量。这可以使用脚本语言来完成,例如 PHP 。类似的东西:

Select distinct(post_id) from table.

然后用您的语言创建循环,例如在 PHP

foreach($query as $value)
  {  // and here,  inside the loop again query the table but with variables:
     set @pid=$value;
     SELECT version, count(*)/(select count(*) from table where post_id=@pid) as                 percentage, post_id FROM `table` where post_id=@pid group by 1
  }

再次回到脚本语言,部署数据。您将获得所请求的百分比,并按每个版本为每个post_id加权。

请测试一下,我按照要求进行测试。