SQL Query将一个状态的计数+所有其他状态统计为一个

时间:2015-03-23 15:59:11

标签: sql sql-server database tsql

我有一个包含一组记录的表。现在通过SQL我得到了每个不同状态的Count。下表中的示例:

    Status      | ID
-------------------------
    Open        | 1
    Open        | 2
    Open        | 3
    Open        | 4
    In Progress | 5
    In Progress | 6
    In Progress | 7
    Closed      | 8
    Closed      | 9
    Closed      | 10
    Closed      | 11

到目前为止,我设法做了以下

Status      | ID
-------------------------
Open        | 4
In Progress | 3
Closed      | 4

但是我希望结果返回

   Status      | ID
-------------------------
   Other       | 7
   Closed      | 4

以下是我目前的SQL:

SELECT myStatus,Count(job) As CountJobs
FROM JobsTable
GROUP BY myStatus
ORDER BY CountJobs DESC

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:3)

使用CASE表达式:

SELECT  CASE WHEN myStatus = 'Closed' THEN 'Closed' ELSE 'Other' END myStatus,
        COUNT(*) CountJobs
FROM JobsTable
GROUP BY CASE WHEN myStatus = 'Closed' THEN 'Closed' ELSE 'Other' END;

答案 1 :(得分:2)

SELECT CASE 
           WHEN Status = 'Closed' 
           THEN Status 
       ELSE 'OTHER' 
       END  AS Status,
       Count(job) As CountJobs
FROM   JobsTable
GROUP BY CASE 
           WHEN Status = 'Closed' 
           THEN Status 
       ELSE 'OTHER' 
       END
ORDER BY CountJobs DESC

答案 2 :(得分:1)

您可以修改查询以使用CASE语句将Closed以外的任何内容替换为子查询中的Other,并GROUP结果:

SELECT  [Status] ,
        COUNT([Status]) StatusCount
FROM    ( SELECT    CASE WHEN [Status] != 'Closed' THEN 'Other'
                         ELSE [Status]
                    END AS [Status]
          FROM      JobsTable
        ) t
GROUP BY [Status]
ORDER BY StatusCount DESC   

完整的可测试查询:

CREATE TABLE #JobsTable
    ([Status] varchar(11), [ID] int)
;

INSERT INTO #JobsTable
    ([Status], [ID])
VALUES
    ('Open', 1),
    ('Open', 2),
    ('Open', 3),
    ('Open', 4),
    ('In Progress', 5),
    ('In Progress', 6),
    ('In Progress', 7),
    ('Closed', 8),
    ('Closed', 9),
    ('Closed', 10),
    ('Closed', 11)
;

SELECT  [Status] ,
        COUNT([Status]) StatusCount
FROM    ( SELECT    CASE WHEN [Status] != 'Closed' THEN 'Other'
                         ELSE [Status]
                    END AS [Status]
          FROM      #JobsTable
        ) t
GROUP BY [Status]
ORDER BY StatusCount DESC   

DROP TABLE #JobsTable

<强>产地:

Status  StatusCount
Other   7
Closed  4

Demo SQL Fiddle

答案 3 :(得分:0)

另一个解决方案:使用WITH子句如下

WITH src AS (
  SELECT CASE WHEN status = 'Closed' THEN 'Closed'
         ELSE 'Other'
         END as Status,
         Id
    from JobsTable)
SELECT src.Status, count(src.Id)
  FROM src
 GROUP BY src.Status;