1

如果我有一个带有状态字段的表,并且我想知道每个状态有多少条记录,我可以做一个简单的分组。如果我想知道 2 条记录的计数和所有其他记录的计数如何。

换句话说,我想要这个:

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

但是失败失败在桌子上,它包含实际的错误消息,所以我想要与成功运行不同的一切not

4

3 回答 3

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 
于 2012-05-03T13:49:41.120 回答
3

单击此处查看 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
于 2012-05-03T14:07:44.653 回答
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

在此处输入图像描述

于 2012-05-03T13:48:46.120 回答