【问题标题】:Find relative percentage查找相对百分比
【发布时间】:2020-04-15 03:14:45
【问题描述】:

我有一个来自用户的投票。例如:

你想要一辆菲亚特吗?

id | answer
1    yes
2    no 
3    yes
...
25   no

count = 20 yes / 5 no

(20 * 100) /25 = 80% Yes
(5 * 100) /25 = 20% No

因此,80% 的人想要菲亚特,20% 的人不想要。显然我可以这样做:

select answer, count(*) as total from fast_survey group by answer;

但是,这将显示计数,我正在寻找相对百分比。知道我该怎么做吗?

【问题讨论】:

  • 与往常一样,实际的表定义(CREATE TABLE 语句)和 Postgres 版本将是有帮助的。

标签: sql postgresql aggregate percentage


【解决方案1】:
SELECT round(count(*) FILTER (WHERE answer)     * 100.0 / count(*), 2) AS pct_yes
     , round(count(*) FILTER (WHERE NOT answer) * 100.0 / count(*), 2) AS pct_no
FROM   fast_survey;
pct_yes | pct_no --------+------- 80.00 | 20.00

db小提琴here

我乘以100.0(不是100)来避免整数除法。结果是numeric 类型,可以将其馈送到round() 以进行美化。见:

假设answerboolean。否则,适应。

聚合 FILTER 子句已在 Postgres 9.4 中引入。见:

应该尽可能快。

【讨论】:

    【解决方案2】:

    您可以COUNT 在分区上获取每种答案类型的值:

    SELECT DISTINCT answer,
           COUNT(*) OVER (partition BY answer) AS total,
           COUNT(*) OVER (partition BY answer) * 100 /
           COUNT(*) OVER () AS percentage
    FROM fast_survey
    

    Demo on SQLFiddle

    如果您希望百分比更精确(对于上述查询,它是整数除法),请将第一个 COUNT 转换为 FLOAT

    SELECT DISTINCT answer,
           COUNT(*) OVER (partition BY answer) AS total,
           CAST(COUNT(*) OVER (partition BY answer) AS FLOAT) * 100 /
           COUNT(*) OVER () AS percentage
    FROM fast_survey
    

    Demo on SQLFiddle

    【讨论】:

      【解决方案3】:

      比如:

      SELECT 
          t1.answer, t1.votes / t2.total_votes
      FROM
          (SELECT answer, count(*) AS votes FROM fast_survey GROUP BY answer) AS t1,
          (SELECT count(*) AS total_votes FROM fast_survey) AS t2
      ;
      

      如果您的调查有多个答案,这也将起作用。

      【讨论】:

        【解决方案4】:

        只需将它与您在不区分答案和计数百分比的情况下计算所有记录的表连接起来......像这样

        select answer, count(*) / max(totalCount) * 100 as total from fast_survey group by answer
        left join (select count(*) FROM fast_survey as totalCount) as all on true
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 2020-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多