SQL查询获取与group by的平均值

时间:2014-02-04 17:33:31

标签: sql group-by sum average

我需要计算平均值。雇员为每组员工每周工作的小时数。我拥有的数据是timeinseconds,empID,Dept。work和date working。 像这样:

PName  EmpID  DeptLoc DeptName TimeinSec  ApplyDate

JRoyce  12345  900    10569    17820      2012-05-10 00:00:00.000   

我有这个查询按周计算总数。但我无法弄清楚如何获得平均值。按周计算的小时数。任何帮助表示赞赏:

select PName, EmpID, DeptLoc, DeptName, Sum(timeinsec/3600.0) as Totalhrs, (Datepart(WK,applydate))
 from EmpTable
Group by PName, EmpID, DeptLoc, DeptName, (Datepart(WK,ApplyDate))
Order by EmpID, WeekNo

它给了我想要TotalHrs的结果:

EmpName   EmpID  DeptLoc   DeptID  TotalHrs WeekNo

JRoyce    12345  900       10569   14.9166  27
JRoyce    12345  900       10569   18.0666  28

现在我希望按周平均按empID小时对这些进行分组,以便显示第27周,第28周等的平均小时数。

我尝试使用内部查询,但它给了我平均所有TotalHrs。

3 个答案:

答案 0 :(得分:0)

将总小时数除以本周工作天数。请参阅以下“平均小时数”计算。

select  PName
        , EmpID
        , DeptLoc
        , DeptName
        , Sum(timeinsec/3600.0) as Totalhrs
        , Sum(timeinsec/3600.0) / Count(applydate) as AvgHours
        , (Datepart(WK,applydate))
from EmpTable
Group by 
        PName
        , EmpID
        , DeptLoc
        , DeptName
        , (Datepart(WK,ApplyDate))
Order by 
        EmpID
        , WeekNo

答案 1 :(得分:0)

试试这个:

SELECT a.PName, a.DeptLoc, a.DeptName, (Datepart(WK,ApplyDate)) [Week], Avg(Totalhrs) as Avghrs
FROM(
select PName, EmpID, DeptLoc, DeptName, Sum(timeinsec/3600.0) as Totalhrs, (Datepart(WK,applydate))
 from EmpTable
Group by PName, EmpID, DeptLoc, DeptName, (Datepart(WK,ApplyDate))
) a
GROUP by a.PName, a.DeptLoc, a.DeptName, (Datepart(WK,ApplyDate))

答案 2 :(得分:0)

如果您想要每周的平均时数,请从empid移除group by

select Datepart(WK,applydate) as weeknum,
       Sum(timeinsec/3600.0) as Totalhrs / count(distinct empid) as avgHrsPerEmployee
from EmpTable
Group by Datepart(WK,ApplyDate)
Order by WeekNum;

平均值是通过总计所有时间并除以员工人数来确定的。