gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:16:42 24 4
gpt4 key购买 nike

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

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

我们可以运行以下 SQL:

select questionid, answerid, count(respondentid) as noOfRespondentsToQuestionAndAnswer
from response
group by questionid, answerid

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

我们还可以:

select questionid, count(distinct respondentid) as noOfRespondentsToQuestion
from response
group by questionid

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

我想将两个选择合并为一个,并让不同受访者的数量在每个问题 ID 的不止一行中表示(这是必要的,因为它仅基于问题而不是答案)。

所以,我想要如下结果:

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

是否可以仅通过一个查询来实现这一目标?

最佳答案

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;

关于sql - 将两个小查询(按不同值分组)合并为一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1806365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com