基于Name的SQL分组

时间:2015-02-06 16:47:03

标签: sql sql-server sql-server-2008-r2

我在SQL Server 2008 R2上运行以下语句:

DECLARE @Customer nvarchar(100);
SET     @Customer = 'Test';

SELECT  
    ProblemCategorization as 'Category'
    , COUNT(ProblemCategorization) as 'Count'
FROM 
    ININ_ISupport_S_Incident_Search2 (NULL) i  
WHERE 
    IncidentType IN ('Customer Support','Managed Services')
    AND i.Organization = @Customer
    AND i.IsResolved = 0
    AND i.Active = 1
    AND i.StateType = 'Open'
GROUP BY 
    i.ProblemCategorization

结果如下

Client Team 1
Client Team_IC Business Manager 3
Client Team_Interaction Attendant   1
Client Team_Interaction Client .NET 3
Client Team_Session Manager 1

我想从每个计数中计算总计数,然后将其分组为一个结果集

Client Count

2 个答案:

答案 0 :(得分:1)

试试这个。

DECLARE @Customer NVARCHAR(100);

SET @Customer = 'Test';

SELECT CASE
         WHEN i.ProblemCategorization LIKE '%client%' THEN 'client'
       END                          AS 'Category',
       Count(ProblemCategorization) AS 'client Count'
FROM   Inin_isupport_s_incident_search2 (NULL) i
WHERE  IncidentType IN ( 'Customer Support', 'Managed Services' )
       AND i.Organization = @Customer
       AND i.IsResolved = 0
       AND i.Active = 1
       AND i.StateType = 'Open'
GROUP  BY CASE
            WHEN i.ProblemCategorization LIKE '%client%' THEN 'client'
          END 

答案 1 :(得分:0)

你有没有看过ROLLUP

尝试一下:

DECLARE @Customer nvarchar(100);
SET     @Customer = 'Test';
SELECT  ProblemCategorization as 'Category'
    , COUNT(ProblemCategorization) as 'Count'
FROM ININ_ISupport_S_Incident_Search2 (NULL) i  
WHERE IncidentType IN ('Customer Support','Managed Services')
AND     i.Organization = @Customer
AND     i.IsResolved = 0
AND     i.Active = 1
AND     i.StateType = 'Open'
Group By i.ProblemCategorization with rollup