在SQL查询中使用GROUP BY的麻烦

时间:2015-06-27 20:53:48

标签: sql sql-server tsql

我试图在MS SQL Server中编写一个propper SQL查询。 首先,我有以下表格:城镇,员工,地址。几乎每个员工都有Manager,ManagerID也是Employees的外键。 (自我关系)我的目标是显示每个城镇的经理人数。到目前为止我有这个代码:

SELECT t.Name, COUNT(*) AS [Managers from each town] 
FROM Towns t
JOIN Addresses a
ON t.TownID = a.TownID
JOIN Employees e
ON a.AddressID = e.AddressID
GROUP BY t.Name
ORDER BY [Managers from each town] DESC

此查询返回每个城镇的员工人数,而不是经理人。 如果我尝试下面的第二个查询,我会得到一些完全错误:

SELECT t.Name, COUNT(*) AS [Managers from each town] 
FROM Towns t
JOIN Addresses a
ON t.TownID = a.TownID
JOIN Employees e
ON a.AddressID = e.AddressID
JOIN Employees m
ON e.ManagerID = m.ManagerID

GROUP BY t.Name
ORDER BY [Managers from each town] DESC

以下是'员工'的结构。表:

EmployeeID,FirstName,LastName,MiddleName,JobTitle,DepartamentID,ManagerID,HireDate,Salary,AddressID

正确的查询必须返回此结果集:

Town          | Managers from each town
Issaquah      | 3
Kenmore       | 5
Monroe        | 2
Newport Hills | 1

4 个答案:

答案 0 :(得分:1)

如果我正确理解您的结构,那么员工是经理的唯一指示是,其ID是否用作其他员工的经理人。您的第一个查询已正确显示计数,然后所需的只是使用

等过滤结果
where EmployeeID in (select ManagerID from Employees)

因此将您的第一个查询转换为:

SELECT t.Name, COUNT(*) AS [Managers from each town] FROM Towns t
JOIN Addresses a
ON t.TownID = a.TownID
JOIN Employees e
ON a.AddressID = e.AddressID
where EmployeeID in (select ManagerID from Employees)
GROUP BY t.Name
ORDER BY [Managers from each town] DESC

答案 1 :(得分:0)

我认为原始查询的以下变体应该是居住在每个城镇的经理:

SELECT t.Name, COUNT(DISTINCT e.EmployeeId) AS [Managers from each town]
FROM Towns t JOIN
      Addresses a
      ON t.TownID = a.TownID JOIN
      Employees e
      ON a.AddressID = e.AddressID
WHERE e.EmployeeId IN (SELECT e2.ManagerId FROM Employees e2)
GROUP BY t.Name
ORDER BY [Managers from each town] DESC;

DISTINCT可能没有必要,但如果不更好地理解数据结构,很难说。

答案 2 :(得分:0)

尝试:

System.String[]

答案 3 :(得分:0)

您可以尝试以下查询来获取所需的输出...

select t.TownName, COUNT(*) as No from Town t
Inner Join Address a on a.TownID = t.TownID
inner join Employee e on e.ManagerID = a.EmployeeID
Group By t.TownName