'Filtered count and total count 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 any simple way to find COUNT WHERE result = 'fail' AND total COUNT.
Expected output:
FailCount TotalCount
-----------------------
4 6
Yes, we can do this using subquery like this:
SELECT
(SELECT COUNT(result) FROM t WHERE result='fail') AS FAILCount
, COUNT(result)
AS TotalCount FROM t;
But is there any way to do like this:
SELECT COUNT(WHERE Result='fail') , COUNT(Result) FROM ...
Solution 1:[1]
And yes we can also use COUNT like this:
SELECT
COUNT(CASE WHEN Result='fail' THEN 1 ELSE NULL END) ,
COUNT(*) FROM ...
Solution 2:[2]
SELECT
SUM(CASE WHEN Result='fail' THEN 1 ELSE 0 END) as FailCount,
COUNT(Result) as TotalCount FROM table_name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Hiren Soni |
