Select条数最少的记录

Select the record with minimum count

我的设置如下:

Table - Tasks

| ResourceID |   Name   | T_SEQ | 
|    1       |  Res1    |   90  |
|    1       |  Res1    |   91  |
|    2       |  Res2    |   92  |

我是运行以下的人:

select ResourceID, COUNT(ResourceID) 
from Tasks 
group by ResourceID

这表明 Res1 的计数为 2,Res2 的计数为 1。

现在我想获得最小值,所以在这种情况下我需要获得 2 的 ResourceID,因为它只有 1 个工作,但我不确定如何去做?

感谢任何能提供帮助的人。

一种方法是order bytop:

select top 1 ResourceID, COUNT(ResourceID) 
from Tasks 
group by ResourceID
order by COUNT(ResourceID);

您可以使用 CTE 解决这个问题。这将为您提供具有最小计数的所有行:

; WITH occurrences AS
(
    select ResourceID, COUNT(ResourceID) AS Counts
    from Tasks 
    group by ResourceID
)
, min_occurrences AS
(
    SELECT MIN(Counts) AS min_counts FROM occurrences
)
SELECT ResourceID FROM occurrences a
INNER JOIN min_occurrences b ON a.Counts = b.min_counts