mysql - 计算子查询 SQL 的百分比

标签 mysql sql database

我有一个表记录有关电子邮件事件的事件。我想计算出在该事件中发生了多个事件的事件所占的百分比。

首先,我计算了每个事件中发生的事件数量:

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/

相关文章:

mysql - 与多列的一对多关系

c++ - 文件同步库

c# - Mysql连接到服务器没有任何数据库

php - 如何将2个数组插入mysql数据库中的2列、不同行?

mysql - SQLYog 自动将 LIMIT 0, 1000 附加到所有查询

mysql - 如何将 SQL Server 游标转换为 MySQL 等效项

sql - Oracle SQL技术避免填充事务日志

mysql - 在单个查询中使用 DISTINCT 两次是否有效

mysql - 为什么我不断收到错误 1005 : Can't create table (errno: 150)?

sql - 查找序列中未缺失的列中的上一个数字