如何在MySQL的计算响应时间和平均首次响应时间与日期过滤器型的基础上“

问题描述 投票:0回答:1

我有两个表命名联系人和邮件。每个接触有两种类型的传入和传出消息的。我想要做的是计算之间的平均时间差的第一个输入和之后要在联系人表中的每个接触第一传入的消息后,也忽略任何传入的消息第一个传出消息通过以下过滤器今天计算的话:从那个00:00被要求一天,直到该数据。昨日:从00:00至23:59被要求提供数据的前一天。最近14天:最近14天最近30天(不含申请提出之日。):最近30天(不含有人要求日)下面是我的表的DB结构。

联系表:

|id    |name      |created_at         |
--------------------------------------
|   1  | Alex     |2019-01-31 00:27:9 |
|   2  | Ammy     |2016-01-31 04:12:9 |

消息表:

|id    |type     |contactId  |created_at         |
--------------------------------------------------
|   1  |  incoming    |  1   |2019-01-31 00:27:16|
|   2  |  incoming    |  1   |2019-01-31 00:27:20|
|   3  |  outgoing    |  1   |2019-01-31 02:37:16|
|   4  |  outgoing    |  1   |2019-01-31 02:37:25|
|   5  |  incoming    |  1   |2019-01-31 03:47:04|
|   6  |  outgoing    |  1   |2019-01-31 03:50:04|
|   7  |  incoming    |  2   |2016-01-31 04:12:16|
|   8  |  outgoing    |  2   |2016-01-31 04:13:16|

预期结果

|contactId |averageTime(min) |
-------------------------
|   1      | 66.5             |
|   2      | 1               |
mysql laravel
1个回答
0
投票

假设你的结果集是错误的...

SELECT contactid
     , SEC_TO_TIME(AVG(diff)) averagetime
  FROM 
     ( SELECT a.contactid
            , MIN(TIME_TO_SEC(b.created_at))-TIME_TO_SEC(a.created_at) diff
         FROM 
            ( SELECT i
                   , contactid
                   , type
                   , MIN(created_at) created_at 
                FROM 
                   ( SELECT contactid
                          , type
                          , created_at
                          , CASE WHEN @prev = type THEN @i:=@i ELSE @i:=@i+1 END i
                          , @prev:=type 
                       FROM message
                          , (SELECT @prev:=null,@i:=0) vars 
                      ORDER 
                         BY contactid,id
                   ) x 
               GROUP 
                  BY i
                   , contactid
                   , type
            ) a
         JOIN message b
           ON b.contactid = a.contactid 
          AND b.created_at >= a.created_at
        WHERE a.type = 'incoming'
          AND b.type = 'outgoing'
        GROUP
           BY a.contactid
            , a.created_at
      ) n
  GROUP
     BY contactid;
© www.soinside.com 2019 - 2024. All rights reserved.