开发者

In TSQL, how to order by "most occurring" values?

开发者 https://www.devze.com 2023-03-05 01:39 出处:网络
Using AdventureWorks, for example, I want to get a list of all employees and their managers, with the managers having the most subordinates at the top.Easy enough to get the number of reports each man

Using AdventureWorks, for example, I want to get a list of all employees and their managers, with the managers having the most subordinates at the top. Easy enough to get the number of reports each manager has by usin开发者_开发技巧g a GROUP BY, but I want the actual list of their subordinates, on separate rows.

SELECT
  Subordinate.LoginID, Subordinate.Title, Manager.LoginID, Manager.Title
FROM
  HumanResources.Employee Subordinate
  JOIN HumanResources.Employee Manager
    ON Subordinate.ManagerID = Manager.EmployeeID
ORDER BY 
  ??


Assuming you are on at least SQL Server 2005 you can use

ORDER BY COUNT(*) OVER (PARTITION BY Manager.LoginID)  DESC

Although I suppose

ORDER BY COUNT(*) OVER (PARTITION BY Manager.LoginID) DESC,  Manager.LoginID

might be better to avoid potentially mingling result rows for managers with tied numbers of subordinates.

0

精彩评论

暂无评论...
验证码 换一张
取 消