按计数排序(someRecord)

时间:2014-05-20 10:34:42

标签: sql sql-server-2008

我有一个包含许多记录的表。列为Directory, Full Name, Server Name。我想查询返回一个记录列表,这些记录按目录列的重复值数排序。

例如:

Directory      Full Name          Server Name
oneill         Liam O'Neill       server1
oneill         Liam O'Neill       server6
oneill         Liam O'Neill       server12
oneill         Liam O'Neill       server2
brown          Joe Brown          server4
brown          Joe Brown          server5
brown          Joe Brown          server2
walsh          Sarah Walsh        server1

3 个答案:

答案 0 :(得分:2)

SELECT   full_name, server_name, COUNT(directory)
FROM     some_table
GROUP BY full_name, server_name
ORDER BY 3 DESC

答案 1 :(得分:1)

您可以直接在ORDER BY

中使用它
SELECT * FROM dbo.Directory d
ORDER BY (SELECT COUNT(*) FROM dbo.Directory d2
          WHERE d.Directory = d2.Directory) DESC

Demo

如果要对升序进行排序,请将DESC更改为ASC,以便首先使用较少重复的目录。您的样本不太好,因为您已经按重复项(desc)对其进行了排序。

答案 2 :(得分:0)

使用窗口函数:

select t.*, count(*) over (partition by Directory) as cnt
from table t
order by cnt desc;