计算表中String值的百分比

时间:2012-08-28 10:37:37

标签: php mysql sql

我有一张桌子,问题已通过或未通过。

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

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

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

正如我所说,总的菜鸟,它是MYSQL btw。

我不需要隔离产品的%结果,到目前为止我已经得到了这个,并且尝试过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 %'";

1 个答案:

答案 0 :(得分: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;

或者您可以将COUNTCASE一起使用,如下所示:

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

或者您可以将SUMCASE一起使用,如下所示:

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;

See this SQLFiddle