mysql - 修改查询以使用新表代替静态数字范围

标签 mysql sql

我有一个有效的查询(如下所示),我正在尝试合并该查询并使用另一个表来实现更直接的方法,但我不太确定如何解决这个问题。

首先,这是查询:

select
case 
when callingpartyno       in (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
  then callingpartyno
when finallycalledpartyno in (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
  then finallycalledpartyno
end as id
, sum(duration) as total_talk_time_seconds
, round(sum(duration) / 60,2) as total_talk_time_minutes
, sum(if(legtype1 = 1,1,0)) as total_outbound
, sum(if(legtype1 = 2,1,0) and answered = 1) as total_inbound
, sum(if(legtype1 = 2,1,0) and answered = 0) as total_missed
, sum(if(legtype1 = 1, 1, 0)) +                   -- outbound calls
  sum(if(legtype1 = 2, 1, 0))  as total_calls
, now() as time_of_report
, curdate() as date_of_report
from 
  ambition.session a
  join ambition.callsummary b
    on a.notablecallid = b.notablecallid
where 
date(b.ts) >= curdate()
 and (
callingpartyno in (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312
)
 or  finallycalledpartyno in (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312
 )
)
group by
id;

我没有在 16 个号码的范围内查找 callingpartyno 和finally Calledpartyno,而是创建了一个名为 users 的表,其中包含 4 位分机号和名字/姓氏的代理商。我想加入该表并使用它来显示用户的名称和扩展名。

表结构为:

ambition.users
   ID PK NN INT
   extension INT
   firstn  varchar
   lastn varchar

所以我基本上想将我的查询更改为“当在 u.extension 中调用partyno/finally Calledpartyno 时”等。

我需要执行哪种类型的联接来匹配现有查询中的内容,以及如何构建它以仅使用新表而不是范围来保持结果相同?

最佳答案

我期望这样的事情:

select uc.agent as calling_agent, uf.agent as final_agent,
       sum(duration) as total_talk_time_seconds,
       round(sum(duration) / 60, 2) as total_talk_time_minutes,
       sum(legtype1 = 1) as total_outbound,
       sum(legtype1 = 2 and answered = 1) as total_inbound,
       sum(legtype1 = 2 and answered = 0) as total_missed,
       sum(legtype1 = 1) +                   -- outbound calls
       sum(legtype1 = 2)  as total_calls,
       now() as time_of_report,
       curdate() as date_of_report
from ambition.session s join
     ambition.callsummary cs
     on s.notablecallid = cs.notablecallid left join
     users uc
     on ?.callingpartyno = uc.extension left join
     users uf
     on ?.finallycalledpartyno = uf.extension
where date(b.ts) >= curdate() and
      (uc.extension is not null or uf.extension is not null)
group by calling_agent, final_agent;

? 是相应表和列的名称。

关于mysql - 修改查询以使用新表代替静态数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47019093/

相关文章:

mysql - UNIQUE INDEX - 指定的键太长;最大 key 长度为 767 字节

mysql - Logstash 异常预期为第 1 行第 1 列的#、输入、过滤器、输出之一

php - mysql 查询与连接

sql - Sharepoint 工作流程表

sql - LEFT JOIN 使用子查询不返回空结果为 "0"

mysql - 如何获得不在两个日期之间的结果?

php - 在 MySQL 中将多行显示为一行

mysql - 如何在列数据类型为 smallint 时查找年龄

mysql - 如果不为空,如何通过插入文本和其他列中的值的组合来更新 mysql 表中的列?

sql - 更改 Firebird 数据库和表的默认排序规则