如何按两个不同的列对 MySQL 查询进行分组?
How do I group a MySQL query by two different columns?
我正在研究的问题是:
Provide the average answer for questions in broken down by Province and then by Question. You must include the province and the question as well as the average.
示例输出看起来像这样:
Ontario - Do you like blak? - 3.4
Ontario - Do you like flah? - 2.3
Ontario - Do you like rahhggg? - 4.8
Alberta - Do you like flah? - 2.3
Alberta - Do you like rahhggg? - 4.8
到目前为止,我已经尝试按问题列出它们的平均值,但我不知道如何先按省分组。我认为这是一个 JOIN 但我不确定如何布置它。我有:
SELECT survey_question_id, AVG(survey_response)
FROM survey_responses
JOIN survey_responders
ON survey_responses.id = survey_responders.id
WHERE survey_responders.province='Ontario'
GROUP BY survey_question_id;
SELECT province,survey_question_id, AVG(survey_response)
FROM survey_responses
JOIN survey_responders
ON survey_responses.id = survey_responders.id
WHERE survey_responders.province='Ontario'
GROUP BY province,survey_question_id;
如果您需要所有省份,只需像这样删除 Where
SELECT province,survey_question_id, AVG(survey_response)
FROM survey_responses
JOIN survey_responders
ON survey_responses.id = survey_responders.id
GROUP BY province,survey_question_id;
MySQL 中的 GROUP BY 语句决定了查询引擎如何聚合数据。您目前仅按 survey_question_id 分组。由于 ID 都不同,因此您永远不会在结果中得到汇总。
我建议将您的群组更改为:
GROUP BY survey_responders.province, survey_responses.questiontitle
并确保适当地编辑您的 SELECT 语句。
我正在研究的问题是:
Provide the average answer for questions in broken down by Province and then by Question. You must include the province and the question as well as the average.
示例输出看起来像这样:
Ontario - Do you like blak? - 3.4
Ontario - Do you like flah? - 2.3
Ontario - Do you like rahhggg? - 4.8
Alberta - Do you like flah? - 2.3
Alberta - Do you like rahhggg? - 4.8
到目前为止,我已经尝试按问题列出它们的平均值,但我不知道如何先按省分组。我认为这是一个 JOIN 但我不确定如何布置它。我有:
SELECT survey_question_id, AVG(survey_response)
FROM survey_responses
JOIN survey_responders
ON survey_responses.id = survey_responders.id
WHERE survey_responders.province='Ontario'
GROUP BY survey_question_id;
SELECT province,survey_question_id, AVG(survey_response)
FROM survey_responses
JOIN survey_responders
ON survey_responses.id = survey_responders.id
WHERE survey_responders.province='Ontario'
GROUP BY province,survey_question_id;
如果您需要所有省份,只需像这样删除 Where
SELECT province,survey_question_id, AVG(survey_response)
FROM survey_responses
JOIN survey_responders
ON survey_responses.id = survey_responders.id
GROUP BY province,survey_question_id;
MySQL 中的 GROUP BY 语句决定了查询引擎如何聚合数据。您目前仅按 survey_question_id 分组。由于 ID 都不同,因此您永远不会在结果中得到汇总。
我建议将您的群组更改为:
GROUP BY survey_responders.province, survey_responses.questiontitle
并确保适当地编辑您的 SELECT 语句。