如何根据aspirasi\u id计算百分比

np8igboo  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(328)
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

输出
错误的值
我怎么能发每张卡,他总各不在加入。
示例真值
谢谢你

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%
ny6fqffe

ny6fqffe1#

我想你需要把百分比除以 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

演示
或者通过使用join,您可以将上面的内容重写为

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

演示

相关问题