我有一个表,记录有关电子邮件活动的事件。我想弄清楚该广告活动发生了多个事件的广告活动所占的百分比。
首先,我计算了每个广告系列中发生的事件数:
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
你知道我最后一步的错误在哪里吗?
答案 0 :(得分:1)
使用子查询进行总计数和除法
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