减去一个总和得到的值

时间:2017-08-23 19:37:00

标签: mysql sql

我的查询完美无缺,但我需要更改计算的一部分以获得新指标。

目前它正在展示这样的数据(为了空间和时间而删除不必要的列):

ID | Extension | Total Inbound | Total Outbound | Total Missed | Total Calls
----------------------------------------------------------------------------
1      1000          6              1                 2             7

但是,我想将其更改为从入站减去错过。它需要继续添加入站和出站总数,但我正在寻找此输出:

ID | Extension | Total Inbound | Total Outbound | Total Missed | Total Calls
----------------------------------------------------------------------------
1      1000          4              1                 2             7

Insert into test.ambitionLog30Days(Extension, ExtID, Total_Talk_Time_seconds,
       Total_Talk_Time_minutes,Total_Outbound, Total_Inbound, 
       Missed_Calls, Total_Calls, Time_of_report,Date_of_report  )  
    SELECT 
        c.extension 
       ,RESPONSIBLEUSEREXTENSIONID 
       , sum(Duration)  
       , round(sum(Duration) / 60,2) 
       , sum(if(LEGTYPE1 = 1,1,0)) -- Total inbound calls 
       , sum(if(LEGTYPE1 = 2,1,0)) 
       , sum(if(Answered = 1,0,1)) -- Total Missed calls
       , sum(if(LEGTYPE1 = 1,1,0)) + sum(if(LEGTYPE1 = 2,1,0))   as total_calls 
       , b.ts
       , b.ts 
    FROM cdrdb.session a
    INNER JOIN cdrdb.callsummary b
        ON a.NOTABLECALLID = b.NOTABLECALLID
    INNER join cdrdb.mxuser c
        ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
        WHERE b.ts BETWEEN curdate() - interval 30 day and curdate()
    -- WHERE b.ts >= '20170723' and b.ts < '20170823'
    AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
    group by c.extension,b.ts
    ON duplicate key update Total_Talk_Time_seconds =values(Total_Talk_Time_seconds), 
       Total_Talk_Time_minutes =values(Total_Talk_Time_minutes), 
       Total_Outbound = values(Total_Outbound), 
       Total_Inbound = values(Total_Inbound), 
       Missed_calls = values(Missed_calls), 
       Total_Calls = values(Total_Calls),
       Time_of_report = values(Time_of_report); 

我尝试在总入站行中减去- sum(if(Answered = 1,0,1)),但它只是将我的出站列中的值作为负数返回,所以我认为我的语法有些错误。

1 个答案:

答案 0 :(得分:2)

只需进行计算:

SELECT c.extension, 
       RESPONSIBLEUSEREXTENSIONID ,
       sum(Duration),  
       round(sum(Duration) / 60, 2) ,
       sum(LEGTYPE1 = 1 and Answered = 1), -- Total inbound calls 
       sum(LEGTYPE1 = 2), 
       sum(case when Answered = 1 then 0 else 1 end)), -- Total Missed calls
       sum( LEGTYPE1 in (1, 2) ), as total_calls 
       b.ts

我还通过删除if()来简化逻辑。 MySQL允许您将布尔表达式视为数字,其中1表示true,0表示false。请注意,如果sum( Answered <> 1 )永远不是Answered,则可以将错过表示为NULL