I have a table that consists of two columns: question and answer. I currently use this query to get totals for answers:
SELECT *, count(answer) AS total
FROM survey_data
GROUP BY answer (originally said: question)
ORDER BY `total` DESC
It tells me how often an answer has occurred, which is what I want, however I found that some questions had the same answer. This query does not take that in account. How can I refine this query so it will also show the different questions with the same answer, so I know which total belongs to which question.
Thanks,
Ryan
You should use QUESTION in the SELECT, instead of *. This makes it clearer what the total relates to
The query does not and cannot “tell you how often an answer has occurred” – because you are not grouping by answer. The only reason “answer” shows up in the result is because you abused MySQL’s mixing of aggregate (grouped column) and non-aggregate column in the SELECT clause via
*(so you are showing the question, and for each question, a completely arbitrary answer.If you need to know how many times an answer occurs, you need to group by answer instead.
And if you needed both in the same query (which makes no sense – just use two queries one after the other), then a convoluted way (not tested)
EDIT
This may be what you are after, which assumes the table is not normalised and that each answer/question combination can occur many times