选择PostgreSQL中另一列的百分比

问题描述 投票:0回答:1

我想按avfamily进行分组,选择具有离岸价值等于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;

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

sql postgresql group-by percentage
1个回答
0
投票

选择,按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(假)或1(真)。此值的平均值为您提供满足组中条件的记录的比率,为01之间的十进制数,然后您可以乘以100


0
投票

我将其表示为:

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不会决定进行整数除法。

© www.soinside.com 2019 - 2024. All rights reserved.