0

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

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

我有 :

$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 %'";

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

非常感谢,谢谢。

4

1 回答 1

1

尝试这个

//按区域过滤

create table t( id int,  answer varchar(10),Area varchar(10));
insert into t select 1  ,  'pass' , 'Area1';
insert into t select 2  ,  'pass' , 'Area1';
insert into t select 3  ,  'fail' , 'Area1';
insert into t select 4  ,  'fail' , 'Area1';
insert into t select 5  ,  'fail' , 'Area1';
insert into t select 6 ,   'fail' , 'Area2';

SELECT 
        (x.TotalFailedAnswerRecord * 100) /y.TotalRecord AS Fail_percent
FROM
            (   SELECT Area,TotalFailedAnswerRecord = COUNT(answer) 
                FROM t 
                WHERE answer='fail' AND Area = 'Area1' 
                GROUP BY Area
            )x
INNER JOIN
            (   SELECT Area,TotalRecord = COUNT(answer) 
                FROM t 
                WHERE Area = 'Area1'
                GROUP BY Area
            )y ON x.Area =y.Area

//Result
Fail_percent
-------------
60

//按区域、产品筛选

create table t( id int,  answer varchar(10),Area varchar(10),Product varchar(10));
insert into t select 1  ,  'pass' , 'Area1' ,'Product1';
insert into t select 2  ,  'fail' , 'Area1' ,'Product1';
insert into t select 3  ,  'fail' , 'Area1' ,'Product1';
insert into t select 4  ,  'fail' , 'Area1' ,'Product1';
insert into t select 5  ,  'fail' , 'Area1' ,'Product2';
insert into t select 6 ,   'fail' , 'Area2' ,'Product2';

SELECT 
        (x.TotalFailedAnswerRecord * 100) /y.TotalRecord AS Fail_percent
FROM
            (   SELECT Area,Product,TotalFailedAnswerRecord = COUNT(answer) 
                FROM t 
                WHERE answer='fail' AND Area = 'Area1' AND Product = 'Product1' 
                GROUP BY Area,Product
            )x
INNER JOIN
            (   SELECT Area,Product,TotalRecord = COUNT(answer) 
                FROM t 
                WHERE Area = 'Area1' AND Product = 'Product1'
                GROUP BY Area,Product
            )y ON x.Area =y.Area AND x.Product = y.Product

//Result
Fail_percent
-------------
75

希望这可以帮助

于 2012-08-30T04:29:20.773 回答