如何按通用字段分组?

时间:2012-05-03 13:44:09

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

如果我有一个带有状态字段的表,我想知道每个状态的记录数,我可以做一个简单的组。如果我想知道2条记录的计数和所有其他记录的计数,那该怎么样呢。

换句话说,我想要这个:

Status   Count
-------- -----
Success   X
Running   Y
Failure   Z

失败 not 失败 在表中,它包含实际的错误消息,所以我希望所有与成功正在运行

不同的东西

3 个答案:

答案 0 :(得分:3)

select case when Status <> 'Success' 
             and Status <> 'Running' 
            then 'Failure' 
            else Status 
        end Status, 
       count (*) [Count]
from atable
group by case when Status <> 'Success' 
               and Status <> 'Running' 
              then 'Failure' 
              else Status 
          end 

答案 1 :(得分:3)

Click here to view the demo in SQL Fiddle.

脚本

CREATE TABLE errormsgs 
(
    id          INT         NOT NULL IDENTITY
  , statusmsg   VARCHAR(30) NOT NULL
);

INSERT INTO errormsgs (statusmsg) VALUES
  ('Success'),
  ('This is error message 1.'),
  ('Running'),
  ('This is error message 2.'),
  ('This is error message 3.'),
  ('Success'),
  ('Success'),
  ('This is error message 4.'),
  ('Running'),
  ('failure, may be'),
  ('failure, absolutely.');

;WITH statuses AS
(
    SELECT  CASE
                WHEN statusmsg NOT IN ('Success', 'Running') THEN 'Failure' 
                ELSE statusmsg 
            END status
    FROM    errormsgs
)
SELECT      status
        ,   COUNT(status) AS status_count
FROM        statuses 
GROUP BY    status;

输出

STATUS   STATUS_COUNT
-------- ------------
Failure        6
Running        2
Success        3

答案 2 :(得分:1)

SELECT DISTINCT CASE 
                     WHEN [status]='s' OR [STATUS]='r' THEN [status]
                     ELSE 'OTHER'
                END AS STATUS
      ,COUNT(1) OVER(
           PARTITION BY CASE 
                             WHEN [status]='s'
           OR [STATUS]='r' THEN [status] ELSE 'aaa' END
       ) AS 'count'
FROM   tbl2

enter image description here