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

时间:2017-10-30 15:36:59

标签: 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 and finallycalledpartyno,而是创建了一个名为users的表,其中包含4位数的扩展名和代理的名/姓。我想加入该表并使用它来显示用户的名称和扩展名。

表结构是:

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

所以我基本上想要改变我的查询来说"当你在u.extension"中调用partyno / finallycalledpartyno时等

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

1 个答案:

答案 0 :(得分:1)

我希望这样的事情:

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;

?用于表示相应表和列的名称。