选择查询以获取SQL Server中的总记录数

时间:2012-07-24 20:45:51

标签: sql-server

您好我有一张状态栏表。如何使用SQL获取记录总数,具有通过状态的记录总数和具有失败状态的记录总数?

4 个答案:

答案 0 :(得分:2)

这样的事情怎么样:

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

如果这两种状态(通过,失败)是唯一的状态(否则你还需要WHERE Status IN ('fail', 'pass')条件),这将有效 - 而WITH ROLLUP也会给你总数所有状态的行(输出中带有Status = NULL

答案 1 :(得分: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

答案 2 :(得分:0)

您可以使用案例陈述和汇总来执行此操作:

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

答案 3 :(得分:0)

其他几种选择(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;