2009-07-13 70 views
1

我有一個表有單個字段。和它有一個值(3,7,9,11,7,11) 現在我想要一個查詢將選擇發生的次數最少的值,如果有一個與最小出現次數相等的然後使用最小的數字SQL:從出現最少次數的列中檢索值

在這種情況下,答案是3

+0

「最小權重」是什麼意思? – 2009-07-13 11:17:19

+0

最小權重意味着該值應該是最小值 – Santanu 2009-07-13 11:17:59

+0

因此,在出現最少次數的情況下,它也必須是最小值。你是這個意思嗎? – 2009-07-13 11:19:45

回答

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 
2

MySQLPostgreSQL

SELECT * 
FROM (
     SELECT field, COUNT(*) AS cnt 
     FROM mytable 
     GROUP BY 
       field 
     ) q 
ORDER BY 
     cnt, field 
LIMIT 1 
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