获取表列中每个值的计数

时间:2012-04-02 18:01:54

标签: sql sql-server-2005

我正在使用SQL Server 2008,并且我有一个表中包含“状态”列。有五种可能的状态:已提交,正在进行,已删除,已实施,未实施。

我正在尝试编写一个SQL语句,它将返回每个状态的计数但我的代码要么返回数字状态,要么返回特定状态的计数。以下是我的工作内容:

SELECT     COUNT(ServiceAreaID) AS ServiceArea
FROM         Suggestions
WHERE     (ServiceAreaID = 6)

或者这个

SELECT     COUNT(DISTINCT ServiceAreaID) AS ServiceArea
FROM         Suggestions

4 个答案:

答案 0 :(得分:2)

一个人:

SELECT Status, COUNT(*)
FROM dbo.Suggestions
WHERE ServiceAreaID = 6
GROUP BY Status;

为了所有人:

SELECT ServiceAreaID, Status, COUNT(*)
FROM dbo.Suggestions
GROUP BY ServiceAreaID, Status;

答案 1 :(得分:1)

select ServiceAreaID,count(*),status
from suggestion
group by status,suggestion;

答案 2 :(得分:0)

SELECT ServiceAreaID, COUNT(*) AS ServiceArea
FROM Suggestions
GROUP BY ServiceAreaID

这应该给你一个每个服务区id的计数。用您的状态替换组中的服务区域ID(下面包括一个与serviceAreaID分开的状态列,如果需要的话)。

 SELECT ServiceAreaID, status, COUNT(*) AS count
    FROM Suggestions
    GROUP BY ServiceAreaID, status

答案 3 :(得分:0)

我认为你所寻找的是这样的:

SELECT ServiceAreaID, COUNT(ServiceAreaID) AS COUNT
FROM Suggestions
GROUP BY ServiceAreaID

我没有在您的SQL示例中看到Status列,但如果应该是一个,则查询将更像这样:

这个答案与Aaron的答案基本相同,所以如果您正在寻找这个答案,请务必将Aaron标记为答案。

SELECT ServiceAreaID, Status, COUNT(*) AS COUNT
FROM Suggestions
GROUP BY ServiceAreaID, Status