如果我有一个带有状态字段的表,并且我想知道每个状态有多少条记录,我可以做一个简单的分组。如果我想知道 2 条记录的计数和所有其他记录的计数如何。
换句话说,我想要这个:
Status Count
-------- -----
Success X
Running Y
Failure Z
但是失败是失败在桌子上,它包含实际的错误消息,所以我想要与成功和运行不同的一切not
如果我有一个带有状态字段的表,并且我想知道每个状态有多少条记录,我可以做一个简单的分组。如果我想知道 2 条记录的计数和所有其他记录的计数如何。
换句话说,我想要这个:
Status Count
-------- -----
Success X
Running Y
Failure Z
但是失败是失败在桌子上,它包含实际的错误消息,所以我想要与成功和运行不同的一切not
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
脚本:
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
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