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

时间:2009-11-27 01:16:29

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

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

我想将两个选项合并为一个,并且让不同的答复者的数量在每个问题的多行上表示(这是必要的,因为它仅基于问题而不是答案)。 / p>

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

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;