2014-04-15 35 views
0

好的,我必須弄清楚如何僅向部門顯示病情最重的員工。如果一個部門有多名員工病假時間相同,則必須全部顯示。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 
+1

[壞習慣踢:使用舊式JOIN](http://sqlblog.com/blogs/ aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx) - 舊式*逗號分隔的表*樣式列表已停用ANSI - ** 92 ** SQL標準(超過** 20年前**) –

回答

0

一種方法是你的底查詢保存到一個臨時表,並基於「最佳病假時間」,從選擇它取決於你在做什麼其他的最佳解決方案就不一定了。

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 
+0

謝謝。這有很大幫助。但是,我認爲這只是給每位員工分配最高小時數,而不是選擇最多小時數的員工。 – user3533214

+0

最大的小時是按部門。 – user3533214