获取此查询的平均值

时间:2012-07-25 23:43:57

标签: sql tsql

假设我有一个包含以下列的表: EmployeeID, PayEntity, HourWorked, Date其中PayEntity can be 1:Normal, 2:OverTime, etc我如何获得一段时间内工作时数的平均值,例如,如果我们在桌面上有这些数据:

1, 1, 40, 7/25/12
1, 2, 5, 7/25/12
2, 1, 30, 7/25/12

此日期的平均值必须为(40+5)+30/2 -- 37.5

2 个答案:

答案 0 :(得分:3)

尝试使用子选择,您可以在其中找到每位员工每天的总小时数,并使用外部选择来计算每天的平均值:

SELECT Date, AVG(HourWorked) AS HourWorked
FROM 
(
    SELECT Date, SUM(HourWorked) AS HourWorked
    FROM yourtable
    GROUP BY EmployeeId, Date
) T1
GROUP BY Date

查看在线工作:sqlfiddle

答案 1 :(得分:0)

沿着同样的路线,但不知道有AVG功能

SELECT employee_id, total_hours, days, total_hours/days as average, 
FROM (
    SELECT employee_id, SUM(hours) as total_hours, COUNT(date) as days FROM `employee_hours_table` GROUP BY `employee_id`
) data