2009-11-27 111 views
2

請看看下面的表(稱爲響應)舉行。它顯示了受訪者對問題和答案的迴應。結合兩個小查詢(該組由不同的值)到一個查詢

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 

...這將告訴我們許多不同的受訪者是如何回答每一個問題。

我想將這兩個選擇合併爲一個,並讓每個問題(這將是必要的,因爲它只基於問題而不是回答)的不同答覆者的數目在多於一行上表示。

所以,我想類似下面的結果:

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 

是否有可能只用一個查詢來達致這?

回答

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