SQL:从发生次数最少的列中检索值

时间:2009-07-13 11:14:24

标签: sql sql-server

我有一个有一个字段的表。它的值如(3,7,9,11,7,11) 现在我想要一个查询,它将选择出现次数最少的值,如果存在最小出现次数,则使用最小的数字

在这种情况下,答案是3。

3 个答案:

答案 0 :(得分:9)

这样的事情:

SELECT TOP 1 COUNT(*), myField
FROM myTable
GROUP BY (myField)
ORDER BY COUNT(*) ASC

其他:并考虑到打破平局的情况:

SELECT TOP 1 COUNT(*), myField
FROM myTable
GROUP BY (myField)
ORDER BY COUNT(*) ASC, myField ASC

答案 1 :(得分:2)

MySQLPostgreSQL

SELECT  *
FROM    (
        SELECT  field, COUNT(*) AS cnt
        FROM    mytable
        GROUP BY
                field
        ) q
ORDER BY
        cnt, field
LIMIT 1

答案 2 :(得分:0)

假设您正在使用SQL Server:如果您拥有最不频繁号码的关系,并且您希望返回所有关联,那么您可以执行以下操作:

DECLARE @temp table (
    count int,
    myField int
)

INSERT @temp
SELECT COUNT(*), myField
FROM myTable
GROUP BY (myField)

DECLARE @minCount int

SELECT @minCount = MIN(count)
FROM @temp

SELECT count, myField
FROM @temp
WHERE count = @minCount