Filtered Quantity and Total without Subquery

Suppose I have a table like this:

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

Is there an easy way to find COUNT WHERE result = 'fail' AND total COUNT.

Expected Result:

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

Yes, we can do this using a subquery like this:

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

But is there a way to do this:

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

I am trying in this fiddle.

+5
source share
3 answers

ANSI SQL

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

SQLFiddle Demo

MySQL specification (as indicated by eggyal)

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

SQLFiddle Demo

+13
source

And yes, we can also use it like this:

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

See this SQLFiddle

+4
source
SELECT 
   SUM(CASE WHEN Result='fail' THEN 1 ELSE 0 END) as FailCount, 
   COUNT(Result) as TotalCount FROM table_name
0
source

All Articles