0

嗨,我有一个带有状态列的表。如何使用 SQL 获取记录总数、通过状态的记录总数和失败状态的记录总数?

4

4 回答 4

2

像这样的东西怎么样:

SELECT Status, COUNT(*)
FROM dbo.YourTable
GROUP BY Status WITH ROLLUP

如果这两种状态(通过,失败)是唯一的状态(否则您将需要WHERE Status IN ('fail', 'pass')另外一个条件),这将起作用 - 并且WITH ROLLUP还将为您提供所有状态的总行数(Status = NULL在输出中带有 a)

于 2012-07-24T20:47:08.717 回答
1

我会写一个类似于

select 
Count(*) as TotalRecords, 
Sum(case where status = 'Pass' then 1 else 0 end) as PassRecords,
Sum(case where status = 'Fail' then 1 else 0 end) as FaileRecords
from Table
于 2012-07-24T20:51:08.930 回答
0

A couple of other alternatives (SQL Server 2008+):

DECLARE @foo TABLE([status] CHAR(4));

INSERT @foo SELECT 'pass'
UNION ALL SELECT 'pass'
UNION ALL SELECT 'fail';

-- option #1:

SELECT [status], c = COUNT(*)
FROM @foo
GROUP BY GROUPING SETS(([status]), ());

-- option #2:

SELECT [status], c = COUNT(*)
FROM @foo
GROUP BY [status]
UNION ALL 
SELECT NULL, COUNT(*) OVER() FROM @foo;
于 2012-07-24T21:00:06.793 回答
0

您可以使用 case 语句和聚合来做到这一点:

select count(*), sum(case when status = 'pass' then 1 else 0 end) as pass,
       sum(case when status = 'fail' then 1 else 0 end) as fail
from t
于 2012-07-24T20:50:33.280 回答