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

标签 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

我们可以运行以下 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/

相关文章:

sql - 问题 : how to use the current time in a where clause

Java和sql循环优化

sql - 在 Redshift 中将时间戳转换为整数

sql - 在 SSMS 18.2 中调试

mysql - SQL表设计

MySQL:两个不同分组的计数和总计

sql - LINQ to SQL 查询帮助 : Doing a distinct on two columns together?

sql - SQL 中的链表

php - 在 SQL 语句中使用 PHP 变量

mysql - 将一个表转换为另一个行数较少的表?