使用avg函数在SQL中进行查询

时间:2014-02-02 17:33:32

标签: mysql sql

EMPLOYEE(ID_Employee, Employee_name,Job,#ID_Dep)
DEPARTMENT (ID_Dep, Dep_name)
HOLIDAY (#ID_Employee, #Date_B, Days)

待办事项一个查询,列出所有员工的假期(以天为单位)的ID和名称,而不是同一部门和同一职位的同事的平均值。

示例:

IF we have

Sara: ID: 1, Department 12, working as secretary. Has spent 12 days in vacation
Jenna: ID: 9, Department 12, working as secretary. Has spent 10 days in vacation
Anna: ID: 3, Department 10, working as HR. Has spent 15 days in vacation
Jenna: ID: 5, Department 10, working as HR. Has spent 12 days in vacation
John: ID: 10, Department 1, working as consulant. Has spent 10 days in vacation

在这种情况下,查询会列出Sara,Anna和John及其各自的ID。

这是实现此目的的正确方法吗?

我尝试了什么?

我可以列出假期超过所有部门共同工作人员平均值的员工。我不知道如何为每个部门办理。

我的代码

SELECT EMPLOYEE.ID_Client, EMPLOYEE.Client_name
FROM EMPLOYEE
WHERE (SELECT HOLIDAY.Days FROM HOLIDAY > SELECT AVG(HOLIDAY.Days));

1 个答案:

答案 0 :(得分:1)

试试这个:

Select e.*, h.*. t.*
from EMPLOYEE as e
left join HOLIDAY h
on e.ID_Employee = h.ID_Employee
left join (
Select sum(h.Days)/count(distinct e.ID_Employee) as average, d.ID_Dep as dept_id
from EMPLOYEE as e
left join HOLIDAY h
on e.ID_Employee = h.ID_Employee
left join DEPARTMENT d
 on  d.ID_Dep = e.ID_Dep
group by dept
) as t on e.ID_Dep = t.dept_id
where h.Days > t.average

在此处,创建一个派生表(dept),其中包含每个部门员工的平均假期数。现在与员工一起加入派生表,并返回已超过平均假期数的用户(加入dept id上的派生表)

可能需要一些调整。