2012-07-24 99 views

回答

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 
+0

我猜想有可能是在狀態,我們沒有其他的值關心 – automatic 2012-07-26 18:11:11

2

怎麼是這樣的:

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

這會工作,如果這兩個狀態(及格,不及格)是唯一的狀態(否則你需要一個WHERE Status IN ('fail', 'pass')條件還) - 和WITH ROLLUP也將給你行的總數(以輸出與Status = NULL)所有狀態

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 
0

一對夫婦的其他替代品(SQL服務器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;