mysql如何按主题平均和分组结果

时间:2014-08-07 08:52:22

标签: php mysql sql

当我运行这个mysql查询时:

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

我得到了这个结果:

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

从上面的结果来看,我想要的是按主题获得平均持续时间和响应:

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

上面的mysql查询对我来说足够复杂,我不知道如何对结果进行平均和分组。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

这必须给你正在等待的结果:

    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

答案 1 :(得分:0)

试试这个

<强> QUERY

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

SQL FIDDLE HERE