SQL Server:按组计数(一列)

时间:2013-11-21 13:29:20

标签: sql-server stored-procedures count group-by

我是SQL Server的新手,希望您能帮助我完成以下任务:

我有一个包含多列的表,其中一列称为categoryX。 列categoryX 中有不同的类别(文字),我想知道表格中有多少项目+ 列类别中按类别计算的项目数

结果应该是这样的:

categoryA: 10
categoryB: 5
categoryC: 3

等等

到目前为止,我有以下内容 - 这会给我一个按类别分组但不是每个组的计数的列表:

CREATE PROCEDURE [dbo].[FetchRequests]
AS
BEGIN
SET NOCOUNT ON;

SELECT  categoryX
FROM    LogRequests
WHERE   logStatus = 'active'
AND workStatus != 'live'
GROUP BY    categoryX
FOR XML PATH('categoryX'), ELEMENTS, TYPE, ROOT('ranks')
END

非常感谢任何帮助,蒂姆

1 个答案:

答案 0 :(得分:3)

CREATE PROCEDURE [dbo].[FetchRequests]
AS
BEGIN
SET NOCOUNT ON;

SELECT categoryX + ': ' + CONVERT(VARCHAR(10),TotalCount) AS Result
FROM
(
    SELECT  categoryX,
            COUNT(*) AS TotalCount
    FROM    LogRequests
    WHERE   logStatus = 'active'
    AND workStatus != 'live'
    GROUP BY    categoryX
) AS T
FOR XML PATH('categoryX'), ELEMENTS, TYPE, ROOT('ranks')
END