将两个小查询(按不同值组分组)合并为一个查询

San*_*rus 3 sql

请查看下表(称为响应).它显示了受访者对问题和答案的回应.

questionid  answerid    respondentid
       1          10        1
       1          11        2
       1          11        4
       1          12        3
       1          12        5
       2          20        1
       2          20        2
       2          21        2
       2          22        1
       2          22        4
       2          23        1
       2          23        3
       2          24        4
       3          30        2
       3          30        3
       3          30        4
       3          31        1
Run Code Online (Sandbox Code Playgroud)

我们可以运行以下SQL:

select questionid, answerid, count(respondentid) as noOfRespondentsToQuestionAndAnswer
from response
group by questionid, answerid
Run Code Online (Sandbox Code Playgroud)

...这将告诉我们有多少受访者回答了问题+答案的每个组合.

我们也可以这样做:

select questionid, count(distinct respondentid) as noOfRespondentsToQuestion
from response
group by questionid
Run Code Online (Sandbox Code Playgroud)

......这将告诉我们有多少不同的受访者回答了每个问题.

我想将两个选项组合成一个,并且让不同的响应者的数量在每个questionid的多行中表示(这是必要的,因为它仅基于问题而不是答案).

所以,我想得到如下结果:

questionid,answerid,noOfRespondentsToQuestionAndAnswer,noOfRespondentsToQuestion
1   10  1   5
1   11  2   5
1   12  2   5
2   20  2   4
2   21  1   4
2   22  2   4
2   23  2   4
2   24  1   4
3   30  3   4
3   31  1   4
Run Code Online (Sandbox Code Playgroud)

只用一个查询就能实现这个目的吗?

Ale*_*lli 5

select one.questionid, answerid,
       noOfRespondentsToQuestionAndAnswer,
       noOfRespondentsToQuestion
FROM (
select questionid, answerid,
       count(respondentid) as noOfRespondentsToQuestionAndAnswer
from response
group by questionid, answerid) AS one
JOIN (
select questionid, count(distinct respondentid) as noOfRespondentsToQuestion
from response
group by questionid) AS two
WHERE one.questionid = two.questionid;
Run Code Online (Sandbox Code Playgroud)