Mysql - 获取两列的平均值,其中where子句按另一列

时间:2015-12-28 22:57:44

标签: mysql

我有一个Asterisk 13 PBX正在将queue_log转储到MySQL,而我正试图做一些基本的报告 - 具体来说,是代理分解的平均呼叫长度。

目前,我已经得到了这个,但有效但并不包含所有来电:

SELECT `asterisk`.`queue_log`.`agent`, count(`asterisk`.`queue_log`.`event`) AS 'calls_taken', AVG(`asterisk`.`queue_log`.`data2`) AS 'aht'
FROM `asterisk`.`queue_log` 
WHERE `asterisk`.`queue_log`.`event` IN ("COMPLETEAGENT", "COMPLETECALLER") AND
            `time` BETWEEN '2015-12-27' AND '2015-12-28' 
GROUP BY `agent`
ORDER BY `agent` ASC

我遇到的问题是,有其他事件代码(" BLINDTRANSFER"," ATTENDEDTRANSFER")将相关数据存储在data4列中而不是data2

我如何基本上将data2组合用于某些事件,将data4组合用于其他事件,然后获取按agent字段分组的组合数据的平均值?

不幸的是,我无法真正改变应用程序的行为,使其更加一致地存储数据。

1 个答案:

答案 0 :(得分:1)

使用IF内的AVG选择合适的列。

SELECT agent, count(event) AS 'calls_taken', 
    AVG(IF(event in ("COMPLETEAGENT", "COMPLETECALLER") , data2, data4)) AS 'aht'
FROM asterisk.queue_log 
WHERE event IN ("COMPLETEAGENT", "COMPLETECALLER", "BLINDTRANSFER", "ATTENDEDTRANSFER") AND
            time BETWEEN '2015-12-27' AND '2015-12-28' 
GROUP BY agent
ORDER BY agent ASC