使用where / if语句求和/计数以查找现有值

时间:2017-09-25 20:17:45

标签: mysql sql

我正在构建一个用于每周报告的表格,但我从查询开始先了解数据。

下面我有我的主要查询,该查询目前适用于我的总计,但我现有的' Total'列需要一个合作伙伴列,它将显示不同的总数。基本上,这都与电话有关,所以目前我有电话总数(总电话,总错过,总入站,总出站)但我需要一个额外的列,用于计算已知/来自已知的电话数量数据库中的数字。

我有一个名为ambition.ambition_customer_data的表,其中包含一个名为phone_number的字段。所以,如果你在我的查询中看到8行,我需要得到calledpartyno = ambition_customer_data.phone_number OR finallycalledpartyno = ambition_customer_data.phone_number数字的总和或计数,如果这是有道理的。

对于其他专栏,我需要做同样的事情,但我必须将其基于下面的legtype列,但如果我知道如何先做这个,我可以适用于那些人。我希望我能做一个SUM(WHERE叫做partyno IN(从ambition_customer_data中选择phone_number))但这似乎不起作用。

我目前有一份不完整的IF声明。关于我能做到这一点的最好方法的任何提示?

SELECT 
    u.firstn
    , u.lastn
    , c.extension
    , SUM(IF(LEGTYPE1 = 1, 1, 0)) +                   -- outbound calls
            SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) +  -- inbound calls
            SUM(IF(Answered = 1, 0, 1))  AS Total_Calls

    , sum(if calledpartyno =) /*HERE IS MY ISSUE CURRENTLY*/

    , sum(if(Answered = 1,0,1)) AS Total_Missed

    , sum(if(LEGTYPE1 = 2,1,0) and ANSWERED = 1) AS Total_Recieved

    , sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound

    , round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes

    , sum(if(Answered = 1,0,1)) / (SUM(IF(LEGTYPE1 = 1, 1, 0)) +                   -- outbound calls
            SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) +  -- inbound calls
            SUM(IF(Answered = 1, 0, 1)))  * 100 AS Percentage_Missed




      FROM ambition.session a
      INNER JOIN ambition.callsummary b
            ON a.NOTABLECALLID = b.NOTABLECALLID
      INNER join ambition.mxuser c
            ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
      INNER join jackson_id.users u
            on c.extension = u.extension
      WHERE b.ts between curdate() - interval 5 day and now()
      AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
      group by c.extension;

1 个答案:

答案 0 :(得分:1)

你正在寻找类似的东西。

SUM( CONDITION_HERE 那么 COLUMN_TO_SELECT 结束时的情况)AS`SELECTION_NAME`