简体   繁体   中英

mysql how to average and group result by topic

When I run this mysql query:

QUERY

SELECT o.ticket_id, ost_help_topic.topic,TIMESTAMPDIFF( MINUTE, 
ost_ticket.created,ost_ticket.closed ) as duration, TIMESTAMPDIFF(MINUTE, 
MIN(o.created), (SELECT MIN(i.created) FROM ost_ticket_thread i
WHERE o.ticket_id = i.ticket_id
AND i.thread_type = 'R')) as response 
FROM ost_ticket_thread o 
INNER JOIN ost_ticket on o.ticket_id = ost_ticket.ticket_id
INNER JOIN ost_help_topic on ost_ticket.topic_id = ost_help_topic.topic_id
WHERE ost_ticket.dept_id=1
AND ost_ticket.status =  'closed'
GROUP BY o.ticket_id

I got this result:

ticket_id |     topic          |   duration |   response
----------+--------------------+------------+--------------
     1    |     PC Support     |   483      |    6441
     2    |     Email Support  |   477      |    3
     3    |     PC Support     |   144      |    30
     4    |     Email Support  |   293      |    2
     5    |     Email Support  |   22       |    7
     6    |     Email Support  |   103      |    15
     7    |     PC Support     |   33       |    33

From the result above, What I would like is to get the average duration and response by topic like this:

topic          |  avg_duration |  avg_response
---------------+---------------+----------------
Email Support  |  223.75       |    6.75
PC Support     |  220          |    2168

The above mysql query is complicated enough for me that I do not know how to average and group the result. Any help is appreciated.

This must give you the result you are awaiting :

    SELECT ost_help_topic.topic, AVG(TIMESTAMPDIFF( MINUTE , ost_ticket.created, 
    ost_ticket.closed )) as duration, AVG(TIMESTAMPDIFF(MINUTE, MIN(o.created)),
    (SELECT MIN(i.created)
FROM ost_ticket_thread o 
INNER JOIN ost_ticket on o.ticket_id = ost_ticket.ticket_id
INNER JOIN ost_help_topic on ost_ticket.topic_id = ost_help_topic.topic_id
WHERE o.ticket_id IN (
SELECT ost_ticket.topic_id
    FROM ost_ticket 
    WHERE ost_ticket.dept_id=1
    AND ost_ticket.status =  'closed'
) 
GROUP BY ost_help_topic.topic

Try This

QUERY

SELECT topic,
AVG(duration) AS 'avg_duration',
AVG(response) AS 'avg_response'
FROM tickets
GROUP BY topic;

SQL FIDDLE HERE

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