我的表格包含字段id
,person
,question
,answer
。所以它是一个垂直的多对多(?)表......
我想从2个问题中得到答案的人数,按这些问题的答案分开,例如:
(问题1有5个答案(1,2,3,4,5),问题2有2个答案(0,1))
`question_1_answer`, `question_2_answer`, `count`
1, 0, 3
1, 1, 2
2, 0, 2
2, 1, 5
3, 0, 3
3, 1, 4
4, 0, 2
4, 1, 3
5, 0, 2
5, 1, 2
如果我只想查看1个问题(本例中为id 2),我可以这样做:
SELECT
`answer`,
COUNT(DISTINCT `person`) AS "count"
FROM
`table`
WHERE
`question` = 2 AND
`answer` IS NOT NULL
GROUP BY `answer`
其中包括:
`answer`, `count`
1, 5
2, 7
3, 7
4, 5
5, 4
但我无法弄清楚如何做我要求的事情,也不能通过搜索找到这样的例子。非常感谢任何帮助。
答案 0 :(得分:0)
您应首先构建两个表,一个包含问题1的答案,另一个表示问题2的答案。之后,您可以使用person
加入它们并使用count()
函数。
CREATE TABLE question_1 AS
SELECT id, person, answer as question_1_answer FROM table
WHERE question = 1 AND answer IS NOT NULL;
CREATE TABLE question_2 AS
SELECT id, person, answer as question_2_answer FROM table
WHERE question = 2 AND answer IS NOT NULL;
SELECT question_1_answer, question_2_answer, count(DISTINCT person) as count
FROM question_1 JOIN question_2 ON question_1.person = question_2.person
GROUP BY question_1_answer, question_2_answer;
抱歉,我没有测试我的代码。它可能不起作用。
答案 1 :(得分:0)
首先使用条件聚合获取每人的计数。然后计算答案对。
select answer1, answer2, count(*)
from
(
select
person,
max(case when question = 1 then answer end) as answer1,
max(case when question = 2 then answer end) as answer2
from answers
group by person
) persons
group by answer1, answer2
order by answer1, answer2;
如果有更多问题并且您想加快查询速度,可以在内部查询中添加WHERE
子句。
在内部查询中添加HAVING
子句,如果人们只能回答其中一个问题,但您只希望有人回答这两个问题。