选择最小计数的记录

时间:2016-03-18 12:34:03

标签: sql sql-server count min

我有如下设置:

表格 - 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个工作,但我不知道该如何去做?

感谢任何可以提供帮助的人。

2 个答案:

答案 0 :(得分:3)

一种方法是order bytop

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

答案 1 :(得分:0)

您可以使用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