需要SQL Group by Query帮助

时间:2014-01-28 22:22:52

标签: mysql sql

我有一张调查结果表。它基本上包含问题ID,所选的响应以及参与调查的人的用户ID。一些样本数据是 -

Q_ID   /   Response ID   /  Response  /  Username
23     /       14        /    Male    /  testuser1
23     /       14        /    Male    /  testuser2
23     /       15        /   Female   /  testuser3
24     /       16        /    Male    /  testuser2
24     /       17        /   Married  /  testuser3
25     /       19        /  Engineer  /  testuser1
25     /       21        /   Surgeon  /  testuser3

我还有另一个带有问题ID的简单表格,以及实际的相应问题。例如,问题Q_ID 23是“你的性别是什么?”

我可以使用什么查询来获得与此类似的结果 -

Question No  /       Question       /  Response # / Response / Count
23           /  What is your Gender /     14      / Male     / 27
23           /  What is your Gender /     15      / Female   / 14

这是我尝试过的,但它并没有完全符合我的要求..(我是初学者)

 Select a.Q_ID, b.Question, a.response_id, a.response, count(a.response)
 from survey_responses a, survey_questions b 
 where a.Q_ID = b.Q_ID group by count(response)

3 个答案:

答案 0 :(得分:2)

Select a.Q_ID, b.Question, a.response_id, a.response, count(a.response)
from survey_responses a, survey_questions b 
where a.Q_ID = b.Q_ID 
group by  a.Q_ID, b.Question, a.response_id, a.response

按要计算的列进行分组,而不是计数。

编辑:使用连接的新语法...你可能应该像这样创建你的sql(自1992年以来)

SELECT a.Q_ID, b.Question, a.response_id, a.response, count(a.response)
FROM survey_responses a
INNER JOIN survey_questions b ON b.Q_ID = a,Q_ID
group by  a.Q_ID, b.Question, a.response_id, a.response
order by a.Q_ID

另外1次编辑...按顺序排列

答案 1 :(得分:1)

尝试使用这样的JOIN

SELECT a.Q_ID, b.Question, a.response_id, a.response, count(a.response)
FROM survey_responses a
INNER JOIN survey_questions b ON b.Q_ID = a,Q_ID
GROUP BY a.Q_ID
ORDER BY count(a.response)

答案 2 :(得分:1)

需要稍作改动。我相信这应该有效:

Select a.Q_ID, b.Question, a.response, count(a.response)
from survey_responses a, survey_questions b 
where a.Q_ID = b.Q_ID
group by a.Q_id, response