我有一些问题和答案的表格。每个问题可以有0个或多个答案。当您离开表时,您将得到如下内容:
q1 a1
q1 a2
q2 a3
q3 NULL
q4 NULL
q5 a4
q6 NULL
q7 a5
q7 a6
我需要的是答案的数量,以及具有那么多答案的问题的数量。即
number_of_answers number_of_questions_that_have_that_many_answers
0 3
1 2
2 2
Redshift中的哪种SQL查询将解决此问题?
答案 0 :(得分:1)
GROUP BY
的另一级别应该这样做:
SELECT answer_count, COUNT(*) AS number_of_questions
FROM (
SELECT q.id, COUNT(a.id) AS answer_count
FROM questions q
LEFT JOIN answers a ON a.question_id = q.id
GROUP BY q.id
) AS x
GROUP BY answer_count