如何根据aspirasi_id计算百分比

时间:2018-05-14 10:52:03

标签: mysql count percentage

Select aspirasi_id
     , aspirasi_option_id
     , (Count(aspirasi_option_id)* 100 / 
           (Select Count(*) 
              From aspirasi_choices)
       ) as total 
  From aspirasi_choices  
 GROUP 
    BY aspirasi_option_id

输出

wrong value

我如何制作每张卡片,他的每张卡片都没有加入。

示例 true value

之前感谢

table



my expectations
aspirasi_id     | aspirasi_option_id | total 
---------+----------+-------
 52             | 6        |  100.00% 
 53             | 5        |  50.00% 
 53             | 4        |  50.00% 
 
Reality 
aspirasi_id     | aspirasi_option_id | total 
---------+----------+-------
 52             | 6        |  33.33% 
 53             | 5        |  33.33% 
 53             | 4        |  33.33% 




1 个答案:

答案 0 :(得分:1)

我猜您需要按照aspirasi_id划分百分比,在子查询中添加where子句,如WHERE aspirasi_id = a.aspirasi_id

SELECT 
  a.aspirasi_id,
  a.aspirasi_option_id,
  (
    COUNT(aspirasi_option_id) * 100 / 
    (SELECT 
      COUNT(*) 
    FROM
      aspirasi_choices 
    WHERE aspirasi_id = a.aspirasi_id)
  ) AS total 
FROM
  aspirasi_choices a 
GROUP BY a.aspirasi_id,
  a.aspirasi_option_id 

Demo

或者通过使用连接,您可以在上面重写为

SELECT 
  a.aspirasi_id,
  a.aspirasi_option_id,
  COUNT(aspirasi_option_id) * 100 / b.inner_total AS total 
FROM
  aspirasi_choices a 
  JOIN (SELECT 
      aspirasi_id,
      COUNT(*) AS inner_total 
    FROM
      aspirasi_choices 
    GROUP BY aspirasi_id) b USING (aspirasi_id) 
GROUP BY a.aspirasi_id,
  a.aspirasi_option_id 

Demo