获取3个或3个以上员工来自同一城市的员工名单?

时间:2014-01-03 09:32:15

标签: sql sql-server select count group-by

我使用以下查询来查找拥有3名以上员工的城市名称

SELECT M.NAME
FROM MasterCity M
INNER JOIN Employee E ON E.CityID = M.ID
GROUP BY E.CityID
HAVING count(E.CityID) >= 3;

它给我以下错误

Column 'MasterCity.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

出了什么问题。在此先感谢

2 个答案:

答案 0 :(得分:7)

变体#1 -

SELECT MAX(M.Name) AS Name
FROM MasterCity M 
JOIN Employee E ON E.CityID = M.ID
GROUP BY E.CityID
HAVING COUNT(E.CityID) >= 3;

变体#2 -

SELECT M.Name
FROM MasterCity M 
JOIN Employee E ON E.CityID = M.ID
GROUP BY E.CityID, M.Name
HAVING COUNT(E.CityID) >= 3;

答案 1 :(得分:1)

试试这个:

SELECT M.ID, M.Name 
FROM MasterCity M 
INNER JOIN Employee E ON E.CityID = M.ID
GROUP BY M.ID, M.Name 
HAVING COUNT(E.CityID) >= 3;