我想按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;
可能很简单,但是我的大脑在这里空白。
选择,按
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
(真)。此值的平均值为您提供满足组中条件的记录的比率,为0
和1
之间的十进制数,然后您可以乘以100
。
我将其表示为:
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不会决定进行整数除法。