【问题标题】:Select percentage of another column in postgresql在postgresql中选择另一列的百分比
【发布时间】:2020-07-15 15:00:41
【问题描述】:

我想按 avfamily 分组,选择 livingofftheland 值等于 true 的记录数量,并将其作为 perc 值返回。

基本上是第 3 列除以第 2 列乘以 100。

select 

    avclassfamily, 
    count(distinct(malware_id)) as cc, 
    sum(case when livingofftheland = 'true' then 1 else 0 end),  
    (100.0 *  (sum(case when livingofftheland = 'true' then 1 else 0 end)  / (count(*)) ) )  as perc 
from malwarehashesandstrings 
group by avclassfamily  having count(*) > 5000  
order by perc desc;

可能很简单,但我的大脑在这里一片空白。

【问题讨论】:

  • 那么问题出在哪里?
  • distinct 不是一个函数,它是一个集合量词。跳过那些多余的括号,直接写count(distinct malware_id) as cc 让代码更清晰。

标签: sql postgresql group-by percentage


【解决方案1】:

选择按avfamily 分组的具有livingofftheland 值等于true 的记录数量并将其作为perc 值返回。

您可以简单地使用avg()

select 
    avclassfamily, 
    count(distinct(malware_id)) as cc, 
    avg(livingofftheland::int) * 100 as perc 
from malwarehashesandstrings 
group by avclassfamily
having count(*) > 5000
order by perc desc

livingofftheland::int 将布尔值转换为 0 (false) 或 1 (true)。该值的平均值为您提供了组中满足条件的记录的比率,作为01 之间的小数,然后您可以乘以100

【讨论】:

    【解决方案2】:

    我会这样表达:

    select avclassfamily, 
           count(distinct malware_id) as cc, 
           count(*) filter (where livingofftheland = 'true'),
           ( count(*) filter (where livingofftheland = 'true') * 100.0 /
             count(distinct malware_id)
           ) as perc
    from malwarehashesandstrings 
    group by avclassfamily 
    having count(*) > 5000  
    order by perc desc;
    

    请注意,这会将条件聚合替换为 filter,这是 Postgres 支持的 SQL 标准构造。它还将100.0 放在/ 旁边,以确保Postgres 不会决定进行整数除法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多