我想获取数据库中所有部门的平均分数,我有一个查询,它仅获取一个部门的平均分数,有没有办法我可以获取部门的名称和平均分数。 假设我有2个部门(服务器和IT),服务器的平均值是该部门人员的所有分数之和除以部门总数。
这是我的查询,但这只是一个部门的平均值
SELECT SUM(RatingId)/(select COUNT(Id) from Employee where DepartmentId = 5) as Sums
FROM PerformanceReviewRatings pfr join
Employee e
on pfr.EmployeeId = e.Id join
Department d
on d.Id = e.DepartmentId
WHERE pfr.AppraisalId = 1009;
答案 0 :(得分:2)
使用group by
SELECT e.DepartmentId, d.name,
SUM(RatingId)/COUNT(1) as Sums
FROM PerformanceReviewRatings pfr
JOIN Employee e
ON pfr.EmployeeId = e.Id
JOIN Department d
ON d.Id = e.DepartmentId
WHERE pfr.AppraisalId = 1009
GROUP BY e.DepartmentId, d.name
答案 1 :(得分:2)
假设一名员工仅获得一个等级,则不需要子查询或对Department
表的引用:
SELECT e.DepartmentId,
SUM(RatingId)/COUNT(*) as average_rating
FROM Employee e LEFT JOIN
PerformanceReviewRatings pfr
ON pfr.EmployeeId = e.Id AND
pfr.AppraisalId = 1009
GROUP BY e.DepartmentId;
如果您只希望获得具有评级的员工的平均值,而不是您的问题提出的答案(即将未评级的员工视为0
,则:
SELECT e.DepartmentId, AVG(RatingId) as average_rating
FROM Employee e JOIN
PerformanceReviewRatings pfr
ON pfr.EmployeeId = e.Id
WHERE pfr.AppraisalId = 1009
GROUP BY e.DepartmentId
答案 2 :(得分:1)
使用AVG()函数。
this.libraryService.reload.subscribe(()=>{})