基于先前计算的字段计算mysql select字段

kcugc4gi  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(359)

所以我在mysql中有一个电话客户数据库,这个数据库有两个表, customer_master 以及 call_data . 两张table都有一张table customer_id 匹配具有特定属性的单个客户编号的字段。这个 customer_master 表中有客户名称 call_data 具有与唯一客户id关联的大量呼叫数据。我需要创建一个查询,从中获取尝试的本地呼叫数,然后根据呼叫事件获取成功的本地呼叫数(而不是丢弃的呼叫数),并计算平均值。这个 call_data 表有一个 call_event 我基本上需要寻找两种不同事物的领域a) local_call_failure 以及 local_call_success . 我可以创建一个查询,在那里我可以使用 inner join 显示带有 userID , user name ,和 total local attempts ,但是我不知道如何使用计算出的尝试值来计算本地呼叫成功平均值。下面是我如何通过根据 call_event :

SELECT customer_id,
CONCAT(name_first, ' ', name_last) AS 'Customer Name',
COUNT(CM.call_event) AS 'Total Local Attemps'
FROM customer_master CM
INNER JOIN call_data CD ON CM.customer_id = CD.customer_id
AND ((call_event = 'local_call_failure')
     OR (call_event = 'local_call_success') )
GROUP BY customer_id;

现在我可以创建另一个查询来计算成功的本地调用总数,除了 AND 声明,仅包括 call_event = 'local_call_success' . 如果我能想出独立的方法,然后除以平均数 call_success/tota_call_attempts ,这就是我所需要的!在任何其他语言中,这都需要一个循环和五分钟,但sql似乎要困难得多。我需要在同一个查询中完成这两个计算,并将它们并排打印出来,然后为平均值创建另一列。如何做到这一点?根据我收集到的数据,设置一个变量 @var_name := COUNT(CM.call_event) 然后用这个变量在你的 SELECT 语句在sql中是不允许的。
有人能帮我吗?我会永远欠你的债!

9udxz4iz

9udxz4iz1#

在mysql中,您可以执行以下操作:

select cm.customer_id,
       concat(cm.name_first, ' ', cm.name_last) AS `Customer Name`, 
       count(*) as total_attempts,
       sum( cd.call_event = 'local_call_failure' ) as num_failures,
       sum( cd.call_event = 'local_call_failure' ) / count(*) as failure_rate
from customer_master cm join
     call_data cd 
     on cm.customer_id = cd.customer_id and
        cd.call_event in ('local_call_failure', 'local_call_success')
group by customer_id, `Customer Name`;
h5qlskok

h5qlskok2#

使用sql server语法,我相信会非常接近:

select customer_id, CONCAT(name_first, ' ', name_last) AS 'Customer Name', 
COUNT(CM.call_event) AS 'Total Local Attemps',
sum(case when call_event = 'local_call_success' then 1 else 0 end) as 'Success Events',
sum(case when call_event = 'local_call_success' then 1 else 0 end)/COUNT(CM.call_event) as SuccesstRate
from customer_master CM
INNER JOIN call_data CD ON CM.customer_id = CD.customer_id
AND ((call_event = 'local_call_failure')
    OR (call_event = 'local_call_success')
    )
group by customer_id;

相关问题