简体   繁体   中英

Mysql - get average of two columns, with a where clause, grouped by another column

I've got an Asterisk 13 PBX which is dumping the queue_log to MySQL, and I'm trying to do some basic reporting off of it - specifically, the average length of calls broken down by agent.

Presently, I've got this, which works but doesn't contain all the calls:

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

The problem I'm having is that there are other event codes ("BLINDTRANSFER", "ATTENDEDTRANSFER") that store the relevant data in the data4 column instead of data2 .

How can I basically combine data2 for some of the events, and data4 for the other events, and then get an average of the combined data, grouped by the agent field?

Unfortunately, I can't really change the behavior of the application to make it store the data more consistently.

Use IF inside AVG to select the appropriate column.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM