我想在MS SQL Server中編寫一個propper SQL查詢。首先,我有以下表格:城鎮,僱員,地址。幾乎每個員工都有經理,而ManagerID也是員工的外鍵。 (自我關係)。我的目標是顯示每個城鎮的經理人數。到目前爲止,我有這樣的代碼:在SQL查詢中使用GROUP BY的問題
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
這裏是「員工」表的結構:
僱員,名字,姓氏,中間名,JOBTITLE,DepartamentID,經理ID,僱傭日期,工資,AddressID
正確的查詢必須返回這個結果集:如果我理解你的結構共同
Town | Managers from each town
Issaquah | 3
Kenmore | 5
Monroe | 2
Newport Hills | 1
採樣數據將是非常有益的,正如一個SQL小提琴。 –