1

我有一张桌子,上面的问题要么通过要么失败。

我只需要一个 SQL 查询来查找问题 1 的失败百分比在提出的问题总数中的百分比。

我正在尝试这个,但这会出现语法错误 -

$CA001 = "COUNT(CA001Result WHERE CA001Result = "Fail") / COUNT(CA001Result)) From Datable";

正如我所说,总菜鸟,它是 MYSQL 顺便说一句。

我不需要隔离 Product 的 % 结果,到目前为止我已经得到了这个,并且已经尝试过 GROUP by Product 但这没有用,有什么想法吗?

$CA001 = "( SELECT ROUND(100 *  (SELECT count(CA001Result ) from Data_Table where (CA001Result='Fail' AND Product='$product' AND Area='$Area'))/count(CA001Result),2) from Data_Table) AS 'CA001 %'";

再看一遍我需要在下面的地方插入一个 WHERE Product = 'Product' ,但是不太明白把它放在哪里,因为下面不起作用:

$CA001 = "( SELECT ROUND(100 * (SELECT count(CA001Result ) from Data_Table where (CA001Result='Fail' AND Product='$product' AND Area='$Area'))/count(CA001Result WHERE Product = '$product'),2) from Data_Table) AS 'CA001 %'";

4

1 回答 1

5

假设这是您的表:

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

所以你需要使用这样的子查询:

SELECT 100 * 
(SELECT COUNT(answer) FROM t WHERE answer='fail')/COUNT(answer)
AS Fail_percent FROM t;

或者你可以像这样COUNT使用CASE

SELECT 100 * 
COUNT(CASE WHEN answer = 'fail' THEN 1 ELSE NULL END)/COUNT(answer)
AS Fail_percent FROM t;

或者你可以像这样SUM使用CASE

SELECT 100 * 
SUM(CASE WHEN answer = 'fail' THEN 1 ELSE 0 END)/COUNT(answer)
AS Fail_percent FROM t;

或者您可以SUM不使用CASE(仅适用于 MySQL),如下所示:

SELECT 100 * 
SUM(answer = 'fail')/COUNT(answer)
AS Fail_percent FROM t;

看到这个 SQLFiddle

于 2012-08-28T10:49:37.047 回答