2013-03-09 95 views
1

我需要做一個查詢計數有多少員工在有超過1名員工並與員工數量大於或等於6每個部門,我有:如何在MySQL中使用count函數的結果?

Select DepartmentName, count(EmployeeNumber) as "Number of Employees" 
From department d, employee e 
Where d.DepartmentName = e.Department and e.EmployeeNumber <=6 
Group by d.DepartmentName; 

這充滿除了關於有部分的所有要求超過1名員工,有沒有辦法只執行代碼的其餘部分,從第一行返回2或更大的結果?

回答

2

使用HAVING子句。請注意,在整個事情計算完畢後纔會應用它。

Select DepartmentName, count(EmployeeNumber) as "Number of Employees" 
From department d, employee e 
Where d.DepartmentName = e.Department and e.EmployeeNumber <=6 
Group by d.DepartmentName HAVING count(EmployeeNumber) > 1; 
+0

不知道這是否會別名工作。我可能會堅持'有計數(EmployeeNumber)> 1' – Kermit 2013-03-09 17:56:04

+0

@AarolamaBluenk同意。我更新了我的答案。 – 2013-03-09 17:57:40

1

試試這個

Select DepartmentName, count(EmployeeNumber) as "Number of Employees" 
    From department d, employee e 
    Where d.DepartmentName = e.Department 
    Group by d.DepartmentName and e.EmployeeNumber <=6 
    HAVING count(EmployeeNumber) > 1 ; 
+0

這不是被問到的。他指的是員工數量,而不是員工數量。此外,您的方式效率非常低,因爲在接收到所有記錄後應用「HAVING」。 – 2013-03-09 17:57:13

+0

除非我遺漏了某些東西,'e.EmployeeNumber <= 6'位可能放錯了位置。 – 2013-03-11 09:03:44

相關問題