7

假设我有一个这样的表:

ID     Result
-------------
 1  ,  'pass'
 2  ,  'pass'
 3  ,  'fail'
 4  ,  'fail'
 5  ,  'fail'
 6 ,   'fail'

有什么简单的方法可以找到COUNT WHERE result = 'fail' AND total COUNT

预期输出:

FailCount    TotalCount
-----------------------
    4            6

是的,我们可以使用这样的子查询来做到这一点:

SELECT 
(SELECT COUNT(result) FROM t WHERE result='fail') AS FAILCount
, COUNT(result)
AS TotalCount FROM t;

但是有没有办法这样做:

SELECT COUNT(WHERE Result='fail') , COUNT(Result) FROM ...

我正在尝试这个小提琴。

4

3 回答 3

20

ANSI SQL

SELECT 
   SUM(CASE WHEN Result='fail' THEN 1 ELSE 0 END) , 
   COUNT(*) FROM ...

SQLFiddle 演示

MySQL 特定(如 eggyal 所指)

SELECT 
       SUM(Result='fail') , 
       COUNT(*) FROM ...

SQLFiddle 演示

于 2012-08-28T12:22:34.730 回答
4

是的,我们也可以这样使用:

SELECT 
   COUNT(CASE WHEN Result='fail' THEN 1 ELSE NULL END) , 
   COUNT(*) FROM ...

看到这个 SQLFiddle

于 2012-08-28T12:36:50.533 回答
0
SELECT 
   SUM(CASE WHEN Result='fail' THEN 1 ELSE 0 END) as FailCount, 
   COUNT(Result) as TotalCount FROM table_name
于 2012-08-28T12:25:00.267 回答