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
输出
我如何制作每张卡片,他的每张卡片都没有加入。
示例 true value
之前感谢
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%

答案 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
或者通过使用连接,您可以在上面重写为
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