使用MySql,我正在尝试编写查询以查找员工更新案例的平均频率。表名是tgs_doc_his
,我需要使用三列:EmpID,CaseID和ActualDate。员工检查案例,系统将首次输入日期。然后,在案件结束之前,员工可以进行多种不同的历史更新。这些状态是无关紧要的,但我包含了这些信息,以便更容易看到我想要做的事情。
它可能看起来像:
EmpID | CaseID | ActualDate | Status
1 , 1 , 2014-01-01 15:00, Checked Out
1 , 2 , 2014-01-02 08:00, Checked Out
1 , 1 , 2014-01-02 09:00, Attempted
1 , 2 , 2014-01-02 10:30, Delivered
2 , 3 , 2014-01-02 11:00, Checked Out
1 , 1 , 2014-01-02 12:00, Delivered
2 , 3 , 2014-01-02 14:45, Delivered
在这里,您可以看到我有两(2)名员工和三(3)名员工。我如何计算员工在每个案例的整体状态更新之间的平均时间?
实施例。员工1的案例1平均为7.0小时+案例2大道= 2.5小时,所有案件的平均总时间为4.75小时,而员工2的总体平均值为3.75小时。
我希望退回:
ID, AveTime
1, 4.75
2, 3.75
这太挑战了吗?我一直在拔头发。
答案 0 :(得分:0)
SELECT delivered.empID, AVG(delivered.ActualDate - checkout.ActualDate) AS AveTime
FROM tgs_doc_his AS delivered
JOIN tgs_doc_his AS checkout ON delivered.empID = checkout.empID
WHERE delivered.Status = 'Delivered'
AND check.Status = 'Checked Out'
GROUP BY delivered.empID
更新:
select empid, avg(datediff)/3600 AS avetime
from (
select empid,
if(@curemp = empid and @curcase = caseid, unix_timestamp(actualdate)-@prevdate, null) as datediff,
@prevdate := unix_timestamp(actualdate),
@curemp := empid, @curcase := caseid
from tgs_doc_his
cross join (select @curemp := null, @curcase := null, @prevdate := null) vars
order by empid, caseid, actualdate) times
group by empid