使用MySQL的平均天数

时间:2012-07-19 18:37:33

标签: mysql average

我正在尝试获取用户关闭机票与打开“下一张”机票之间的平均天数。

我的MySQL表的示例如下。您会注意到迈克创造了3张门票,相隔9天(7月1日至7月10日)和5天(7月10日至7月15日),平均为7天。我似乎无法弄清楚如何寻找最后解决的日期,任何人都有任何想法? 这就是我到目前为止所做的:

SELECT 
  Name, 
  Created, 
  Resolved, 
  avg(datediff("Last Ticket Resolved", created) AS last_tket_open 
FROM 
  MyTable 
WHERE 
  Name='Mike'


Name   Created  Resolved
----   -------  --------
Mike   July  1   July  1
Jill   July  2   July  3    
Mike   July 10   July 10
Harry  July 11   July 11
Mike   July 15   July 15

3 个答案:

答案 0 :(得分:1)

SELECT a.name, 
       AVG(DATEDIFF(a.resolved, b.created)) AS avgdays
FROM
(
   SELECT name, resolved, @val1:=@val1+1 AS rn
   FROM tbl
   CROSS JOIN (SELECT @val1:=0) val1_init
   WHERE name = 'Mike'
   ORDER BY resolved
) a
INNER JOIN
(
   SELECT created, @val2:=@val2+1 AS rn
   FROM tbl
   CROSS JOIN (SELECT @val2:=1) val2_init
   WHERE name = 'Mike'
   ORDER BY resolved
) b ON a.rn = b.rn

SQLFiddle Demo

答案 1 :(得分:0)

试试这个:

SELECT
  t1.Name,
  AVG( datediff( t2.Created, t1.Resolved )) AS avg_days_between_tickets
FROM
  MyTable t1,
  MyTable t2
WHERE
      t2.Name = t1.Name
  AND t2.Created = ( SELECT MIN( Created ) 
                     FROM MyTable 
                     WHERE Name = t1.Name 
                       AND Created > t1.Resolved )
GROUP BY
  t1.Name

答案 2 :(得分:0)

select 
  Name,
  AVG( datediff( next_created, resolve )) AS avg_time
from (select
  t1.Name,
  t1.Created,
  t1.Resolved,
  min(t2.Created) as next_created
from mytable t1
join myTable t2 on t1.Name = t2.Name and t2.Created > t1.Resolved
group by 1,2,3) x
group by 1;

请注意,此查询不使用相关子查询(由于编码方式依赖于行中的值而对每行执行的查询),因此它应该执行得非常好。