将两个按不同值进行分组的小查询合并为一个查询

3
请查看以下表格(名为response)。它显示了被调查者对问题和答案所给出的回应。
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

这段文字是关于IT技术的,它描述了一种方法来告诉我们有多少人回答了每个问题和答案组合。同时,我们还可以进行以下操作:

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

这将告诉我们每个问题有多少不同的调查对象进行了回答。

我想把这两个选项合并成一个,让每个问题的不同调查对象数量在每个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

这个问题是否可以只用一个查询语句来实现?
2个回答

7
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;

0

您没有指定数据库类型,这会使事情变得简单。但从纯SQL的角度来看,不使用任何分析工具也可以完成,但会失去效率。

select questionid, answerid, 
(select a.count(*) FROM datatable a WHERE a.questionid=questionid AND a.answerid=answerid), 
(select b.count(*) FROM datatable b WHERE b.questionid=questionid)
FROM datatable ORDER BY questionid, answerid;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接