1

希望你能帮忙,这把我逼疯了

我需要计算一个问题失败的百分比,但这需要按地理区域缩小范围,并针对这些问题提出的产品。

我有 :

$CA002 = "( SELECT ROUND(100 *  (SELECT count(CA002Result) from Data_Table where (CA002Result='Fail'))/count(CA002Result),2) from Data_Table) AS 'CA002 %'";

哪个“有效”,但只是针对整个记录集作为“整体”进行计算

我正在努力 :

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

并且 :

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

也在尝试这个,但得到一个 MYSQL 语法错误。

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

并且无论我尝试什么都会出错,我似乎无法弄清楚我需要把什么放在哪里。

尝试了以下答案:

$CA001 = "(SELECT 100 * SUM(IF(CA001Result='Fail', 1, 0)) / COUNT(CA001Result) as 'CA001 %' WHERE  Area='$Area')";

$CA002 = "( SELECT ROUND(100 *  (SELECT count(CA002Result) from Data_Table where (CA002Result='Fail'))/count(CA002Result),2) from Data_Table) AS 'CA002 %'";

但我得到以下错误:

MySQL 错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 ' ( SELECT ROUND(100 * (SELECT count(CA002Result) from Data_Table where (CA002Re' at line 1) 附近使用的正确语法)

非常感谢任何帮助,谢谢。

编辑 - 使用以下方法破解它:

$CA001 ="ROUND ((SELECT 100 * SUM(IF(CA001Result='Fail', 1, 0)) / COUNT(CA001Result) 
FROM Data_Table
WHERE  Area='$Area'),2) as 'CA001 %'";

非常感谢你的帮忙!

4

2 回答 2

2

尝试这个

SELECT 100 * SUM(IF(CA001Result='Fail', 1, 0)) / COUNT(CA001Result) as 'CA002 %'
FROM Data_Table
WHERE '$product' AND Area='$Area'
于 2012-08-29T08:03:40.993 回答
0

我只是在猜测您的模型,但您应该尝试这种模式:

SELECT
    Area,
    Product,
    COUNT(*) as total,
    SUM(CA002Result='Fail') as total_fail,
    SUM(CA002Result='Fail') / COUNT(*) as 'CA002 %'
FROM Data_Table
GROUP BY Area, Product;
于 2012-08-29T08:04:05.070 回答