我有一个表记录有关电子邮件事件的事件。我想计算出在该事件中发生了多个事件的事件所占的百分比。
首先,我计算了每个事件中发生的事件数量:
select count(*) as counter
from campaigns_log
where event IN ('send', 'open')
and campaign_id is not null
group by campaign_id, email
然后,我根据是否发生多个事件对营销事件进行分组:
select count(counter) as occurences, IF(counter > 1, 2, 1) as grouper
from (select count(*) as counter
from campaigns_log
where event IN ('send', 'open')
and campaign_id is not null
group by campaign_id, email) as counters_table
group by grouper
结果示例:
occurences ¦ grouper
132 ¦ 1
360 ¦ 2
现在我想计算每一行的总出现次数的百分比。所以像这样:
occurences ¦ grouper ¦ percentage
132 ¦ 1 ¦ 132/(132+360)
360 ¦ 2 ¦ 360/(132+360)
我尝试了这个,但它不起作用,它无法正确计算总和:
select *, occurences/(select sum(occurences))
from (
select count(counter) as occurences, IF(counter > 1, 2, 1) as grouper
from (select count(*) as counter
from campaigns_log
where event IN ('send', 'open')
and campaign_id is not null
group by campaign_id, email) as counters_table
group by grouper
) as occurences_table group by occurences, grouper
知道我最后一步的错误在哪里吗?
最佳答案
使用子查询进行总数和除法
select a.occurences,a.grouper, (a.occurences/c.total) as percentage
from (select count(counter) as occurences, IF(counter > 1, 2, 1) as grouper
from (select count(*) as counter
from campaigns_log
where event IN ('send', 'open')
and campaign_id is not null
group by campaign_id, email) as counters_table
group by grouper
) a,
(select sum(occurences) total from
(select count(counter) as occurences, IF(counter > 1, 2, 1) as grouper
from (select count(*) as counter
from campaigns_log
where event IN ('send', 'open')
and campaign_id is not null
group by campaign_id, email) as counters_table
group by grouper
) b )c
关于mysql - 计算子查询 SQL 的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771152/