我的mySQL语句:
SELECT DATE(x.created_at), AVG(TIMEDIFF(y.created_at, x.created_at)/60/60)
FROM
(SELECT *
FROM events a
WHERE a.created_at > '12-10-10 12:12:12'
AND a.type = 'Started') x INNER JOIN
(SELECT *
FROM events a
WHERE a.created_at > '12-10-10 12:12:12'
AND a.type = 'Complete') y ON x.target_id = y.target_id
GROUP BY DATE(x.created_at)
ORDER BY DATE(x.created_at)
理想情况下,我试图得到每个日期的运行中位数。因此,对于每个日期,选择created_at
列之间的时间差,并找到该日期所有值之间的中位数TIMEDIFF。依此类推,直到每个日期,只要它们有相应的complete
。
作为一个更短的目标,我上面的代码块只是"平均"(因为我不能算出中位数),每个日期的最后一个返回值,而不是落在该日期的所有。
有任何提示,技巧,答案吗?
给定适合测试的数据,我们的查询似乎可以工作。看看这个修正的SQL Fiddle: http://sqlfiddle.com/#!2/8458d/3/0
但是,查询可以简化为
SELECT DATE(a.created_at),
AVG(TIMEDIFF(b.created_at, a.created_at)/60/60)
FROM events a
INNER JOIN events b
ON a.target_id = b.target_id
WHERE a.created_at > '2012-10-10 12:12:12'
AND a.type = 'Started'
AND b.created_at > '2012-10-10 12:12:12' -- not needed?
AND b.type = 'Completed'
GROUP BY DATE(a.created_at)
ORDER BY DATE(a.created_at)