假设我有一个这样的表:
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 ...
答案 0 :(得分:15)
ANSI SQL
SELECT
SUM(CASE WHEN Result='fail' THEN 1 ELSE 0 END) ,
COUNT(*) FROM ...
MySQL特定(正如eggyal指出的)
SELECT
SUM(Result='fail') ,
COUNT(*) FROM ...
答案 1 :(得分:4)
是的,我们也可以这样使用:
SELECT
COUNT(CASE WHEN Result='fail' THEN 1 ELSE NULL END) ,
COUNT(*) FROM ...
答案 2 :(得分:0)
SELECT
SUM(CASE WHEN Result='fail' THEN 1 ELSE 0 END) as FailCount,
COUNT(Result) as TotalCount FROM table_name