如何在SQL中选择重复次数最少的值

时间:2014-02-12 18:13:37

标签: sql

我有一个包含列

的表格

FacilityID,servername

,facilityID是主键,servername是该工具的数据所在的服务器。

当我们添加新设施时,我希望能够选择使用次数最少的服务器名称,但我不知道该怎么做。

我认为它将使用count函数,但我不确定所涉及的语法。

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

取决于数据库,在mssql中我会这样做:

select top 1  FacilityID,count(servername) over (partition by FacilityID) as Cardinality from tablename order by Cardinality asc

答案 1 :(得分:1)

你可以使用COUNT然后在MIN之外。

Select MIN (x.myCount )
FROM (
  select COUNT (servername) as myCount 
  from ...
  GROUP BY servername) as x

答案 2 :(得分:1)

您可以使用子查询执行此操作:

SELECT TOP 1 * FROM
(
    SELECT servername, COUNT() Cnt
    FROM MyTable
    GROUP BY servername
)
ORDER BY Cnt

答案 3 :(得分:1)

SELECT * TOP 1 
FROM (
    Select servername , Count(FacilityID) as Count
    FROM YourTable
    GROUP BY FacilityID
    ORDER BY Count ASC)