tags:

views:

213

answers:

3

I have a table which have a single field. and it have a values like (3,7,9,11,7,11) Now I want a query which will pick the value that occurred least number of times and if there is a tie with minimum occurrences then use the smallest number

In this case the answer will be 3.

+8  A: 

Something like this:

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

ADDITIONAL: And to taking into account the tie-breaker situation:

SELECT TOP 1 COUNT(*), myField
FROM myTable
GROUP BY (myField)
ORDER BY COUNT(*) ASC, myField ASC
Colin Mackay
+1 Yep, what he said [deleted mine]
Dead account
Updated answer to take into account the tie-breaker aspect of the question.
Colin Mackay
Thanks This works in the SQL server exactly the way I wanted.
santanu
+2  A: 

In MySQL and PostgreSQL:

SELECT  *
FROM    (
        SELECT  field, COUNT(*) AS cnt
        FROM    mytable
        GROUP BY
                field
        ) q
ORDER BY
        cnt, field
LIMIT 1
Quassnoi
Hi Quassnoi U r answer is 98% right Only one need to add <AS tst> as an alias name before the ORDER BY clause.Because in MySql Every derived table must have its own alias.Thanks for the help
santanu
@santanu: right, fixing.
Quassnoi
A: 

Assuming you're using SQL Server: if you have ties for the least frequent number, and you want all ties returned, then you could do something like this:

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
David M