SQL组合语句

时间:2014-04-15 03:43:44

标签: sql

好的,我必须弄清楚如何只按部门向员工显示最高病假时间。如果一个部门有多名员工因病假而被捆绑,则必须向所有员工展示。

第一个查询,给我按SickLeaveHours排序的部门中的每个人。 第二个查询按部门告诉我最高病假时间。

如何根据底部查询获取最高查询以限制结果。

Select FirstName + ' ' + LastName as Name, (SickLeaveHours), Department.DepartmentID as DepartmentID, HumanResources.Department.Name
 FROM HumanResources.Employee, HumanResources.EmployeeDepartmentHistory, Person.Contact, HumanResources.Department
Where Employee.EmployeeID=EmployeeDepartmentHistory.EmployeeID and Employee.ContactID=Contact.ContactID and EndDate is Null  and HumanResources.Department.DepartmentID=EmployeeDepartmentHistory.DepartmentID
Order by SickLeaveHours DESC


Select DepartmentID, Max(SickLeaveHours) as 'Top Sick Leave Hours'
From HumanResources.Employee, HumanResources.EmployeeDepartmentHistory
Where EmployeeDepartmentHistory.EmployeeID=Employee.EmployeeID and EmployeeDepartmentHistory.EndDate is Null
Group by DepartmentID
Order by 'Top Sick Leave Hours' DESC

2 个答案:

答案 0 :(得分:0)

一种方法是将您的底层查询保存到临时表中,并根据" Top Sick Leave Hours"取决于你正在做什么,可能不是最好的解决方案。

答案 1 :(得分:0)

此窗口功能是否适合您?我没有你的环境来测试它,以确保我的语法完全正确...

Select FirstName + ' ' + LastName as Name, 
MAX(SickLeaveHours) OVER (PARTITION BY Department.DepartmentID ) as MaxSickLeaveHours,     
Department.DepartmentID as DepartmentID, HumanResources.Department.Name
 FROM HumanResources.Employee, HumanResources.EmployeeDepartmentHistory, Person.Contact, HumanResources.Department
Where Employee.EmployeeID=EmployeeDepartmentHistory.EmployeeID and Employee.ContactID=Contact.ContactID and EndDate is Null  and HumanResources.Department.DepartmentID=EmployeeDepartmentHistory.DepartmentID
Order by SickLeaveHours DESC