开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜