2个表中行之间的SQL平均值

时间:2016-05-04 22:05:24

标签: mysql

我正在运行此SQL查询:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{{ _charset }}" />
        <title>An Error Occurred: {{ status_text }}</title>
    </head>
    <body>
        <h1>Oops! An Error Occurred</h1>
        <h2>The server returned a "{{ status_code }} {{ status_text }}".</h2>

        <div>
            Something is broken. Please let us know what you were doing when this error occurred.
            We will fix it as soon as possible. Sorry for any inconvenience caused.
        </div>
    </body>
</html>

数据库架构

select sec_to_time(avg(time_to_sec(timediff(u.datetime, t.datetime)))) as time FROM tickets t 
                        JOIN ticket_updates u ON 
                        t.ticketnumber = u.ticketnumber 
                            WHERE 
                                DATE(t.datetime) = '2016-05-05' AND 
                                t.customer='Y' AND 
                                u.type='update'
                        ;

一些示例数据

tickets
   ticketnumber -> INT
   datetime -> DATETIME
ticket_updates
   ticketnumber -> INT
   datetime -> DATETIME

我正在寻找所有门票的平均响应时间。这将基于每张票的第一次更新 - 所有其他票都无关紧要。

对于这些数据,那将是2:30小时:

  1. 对于票1234,响应时间为3小时(创建9:00,首次更新为12:00)
  2. 对于故障单1235,响应时间为2小时(创建11:00,首次更新为13:00)
  3. 然后平均值为(3 + 2)/ 2 = 2.5

    当前输出基于tickets ticketnumber datetime 1234 '2016-04-28 09:00:00' 1235 '2016-04-28 11:00:00' ticket_updates ticketnumber datetime 1234 '2016-04-28 12:00:00' 1234 '2016-04-28 15:00:00' 1235 '2016-04-28 13:00:00' 1235 '2016-04-28 16:00:00' 中的所有行,但我只希望它查看ticket_updates中最早添加的行

    请指导我如何让它像那样工作。

1 个答案:

答案 0 :(得分:1)

好的,试试看,让我知道它是怎么回事。

SELECT SEC_TO_TIME(AVG(time_diff)) as avg_response_time 
FROM(
   SELECT TIMESTAMPDIFF(SECOND,t.datetime, MIN(u.datetime)) as time_diff
   FROM tickets as t
   JOIN ticket_updates as u on u.ticketnumber= t.ticketnumber
   WHERE 
     DATE(t.datetime) = '2016-05-05' AND 
     t.customer='Y' AND 
     u.type='update'
   GROUP BY t.ticketnumber
) AS a;