简体   繁体   中英

SQL query to get totals

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

SELECT question, count(answer) AS total
FROM survey_data
GROUP BY question
ORDER BY `total` DESC

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.

SELECT answer, count(answer) AS total
FROM survey_data
GROUP BY answer
ORDER BY `total` DESC

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)

SELECT 'question' as type, question, count(answer) AS total
FROM survey_data
GROUP BY question
UNION ALL
SELECT 'answer' as type, answer, count(answer) AS total
FROM survey_data
GROUP BY answer
ORDER BY type, `total` DESC


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

SELECT answer, question, count(*) AS total
FROM survey_data
GROUP BY answer, question
ORDER BY `total` DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM