Hi
I have a SQL query that counts values in a table and totals them up and
works out a percentage, it involves a few counts, is there a better why
to acheive what I want other than the way I have done it?
The query is:
SELECT q.`text` AS 'Question',
(SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer = 'y')
AS 'Yes',
(SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer = 'n')
AS 'No',
(SELECT COUNT(*) FROM answer WHERE question_id = q.id) AS 'Total',
((SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer =
'y') /
((SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer =
'y') + (SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer
= 'n')) * 100) AS 'Percentage Yes',
((SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer =
'n') /
((SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer =
'y') + (SELECT COUNT(*) FROM answer WHERE question_id = q.id AND answer
= 'n')) * 100) AS 'Percentage No'
FROM question AS q INNER JOIN answer AS a ON q.id = a.question_id WHERE
q.id < 192
GROUP BY q.id ORDER BY q.id ASC
I have a table of questions then a table of what the answer is (either
yes/no in the answer column). I count the amount of y values, then the
n values, then count all of them for a total, then I have to do the
same counts again to acheive a percentage.