简体   繁体   English

SQL查询获取总计

[英]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 *. 您应该在SELECT中使用QUESTION而不是*。 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. 结果中出现“答案”的唯一原因是因为您通过* 滥用了SELECT子句中MySQL的聚合(分组列)和非聚合列的混合(因此,您展示的是问题,对于每个问题,这都是完全任意的回答。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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