【问题标题】:Fetch percentage of total records that have a particular value in postgresql获取 postgresql 中具有特定值的总记录的百分比
【发布时间】:2020-02-03 21:23:57
【问题描述】:

我的 postgresql 数据库中有一张人员表。此表有一个包含值“M”和“F”的“性别”列。我想获取该表中性别为“M”的百分比。

更具体地说,我想获取这个百分比作为 group by 语句的一部分,该语句按邮政编码对人们进行分组(我们有一个邮政编码列)并返回每个邮政编码的男性百分比。

此语句成功获取整个表中的男性数量。

select count(*) from contacts_6  and sex='M'

此语句成功获取每个邮政编码和按邮政编码分组的总人数...

select home_zip,  count(*) as total from contacts_6 where home_zip != '' group by home_zip

此语句成功获取了一个虚拟百分比,该百分比是根据虚拟值 2.0 除以每个邮政编码和按邮政编码分组的总人数...

select home_zip,  ROUND(2.0 / count(*), 3) as stat from contacts_6 where home_zip != '' group by home_zip

如何将虚拟值 2.0 替换为邮政编码中的实际男性人数?

这个我试过了……

select home_zip,  ROUND((select b from 
                    (select count(*) from contacts_6 where contact_id < 10000 and sex='M') as b )
                    / count(*), 3) as stat from contacts_6 where home_zip != '' group by home_zip

返回错误:

错误:操作符不存在:记录/bigint LINE 9: / count(*), 3) as stat from contacts_6 where home_zip ... ^ 提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。 SQL 状态:42883 字符:695

【问题讨论】:

    标签: sql postgresql select


    【解决方案1】:

    你可以做条件聚合:

    select 
        home_zip,  
        1.0 * round(sum( (sex = 'M')::int ) / count(*), 3) as stat 
    from contacts_6 
    where home_zip != '' 
    group by home_zip
    

    sum( (sex = 'M')::int ) 统计组中有多少条记录有sex = 'M';这是通过将条件(truefalse)的结果转换为整数值(10)并对这些值求和来实现的。

    由于我们正在处理0/1 值,另一种方便的计算方法是使用avg()

    select 
        home_zip,  
        round(avg( (sex = 'M')::int ), 3) as stat 
    from contacts_6 
    where home_zip != '' 
    group by home_zip
    

    【讨论】:

      【解决方案2】:

      这似乎可以解决问题。有没有更好的办法?

      select home_zip,  ROUND(avg(case when sex = 'M' then 100.0 else 0.0 end), 3)
       as stat from contacts_6 where home_zip != ''  group by home_zip
      

      我在另一篇文章中找到了答案,关闭了页面并且在我的浏览器缓存中没有 URl。

      【讨论】:

        【解决方案3】:
        select 
           sex, 
           round(count(*)*100/(select count(*) from contacts_6),2) AS Pucentage
        from 
           contacts_6
        group by  
           sex
        having 
           sex = 'M'
        

        【讨论】:

        • 虽然代码可能会解决问题,但一个好的答案还应该解释代码的作用以及它如何提供帮助。你的代码也不适合这个问题。
        • 您好,我知道您是新用户。在 StackOverflow 上,仅代码的答案被认为是不可取的。例如,如果有人没有摆在他们面前的问题,你的回答是否有意义?可能不是。您的问题正在审查中删除。请添加一些文字,用一些词来解释您的答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        相关资源
        最近更新 更多