问题
hope you can help, this is driving me up the wall
I need to calculate the percentage of times a question has been failed, but this needs to be narrowed down by the geographical area, and product these questions are being asked against.
I have :
$CA002 = "( SELECT ROUND(100 * (SELECT count(CA002Result) from Data_Table where (CA002Result='Fail'))/count(CA002Result),2) from Data_Table) AS 'CA002 %'";
Which 'works' but just calculates against the whole set of records as an 'overall'
I'm trying :
$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 %'";
And Also :
$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 %'";
Also Trying this, but get a MYSQL syntax Error.
$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 %')";
and am just getting errors no matter what I try, I just can't seem to work out what I need to put where.
TRied the below answer:
$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 %'";
but am getting the below as an error:
MySQL ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' ( SELECT ROUND(100 * (SELECT count(CA002Result) from Data_Table where (CA002Re' at line 1
Any help GREATLY appreciated, thankyou.
Edit - Cracked it using :
$CA001 ="ROUND ((SELECT 100 * SUM(IF(CA001Result='Fail', 1, 0)) / COUNT(CA001Result)
FROM Data_Table
WHERE Area='$Area'),2) as 'CA001 %'";
Thanks so much for the help!
回答1:
Try this
SELECT 100 * SUM(IF(CA001Result='Fail', 1, 0)) / COUNT(CA001Result) as 'CA002 %'
FROM Data_Table
WHERE '$product' AND Area='$Area'
回答2:
I'm only guessing your model, but you should try this pattern:
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;
来源:https://stackoverflow.com/questions/12173248/calculating-percentage-within-mysql-query-based-on-conditions