Sql 两次合并一个表并计数记录

Sql 两次合并一个表并计数记录,sql,sql-server,database,join,Sql,Sql Server,Database,Join,我有两张桌子。一个是大师,另一个是查阅。 TblMstr和Cmaster Tblmstr Id QuestionId ChoiceId ChoiceMaster 1 2 1 Strongly Agree 1 3 2 Disagree 1 4 3 Agree 1 5 11 null 2 2 2

我有两张桌子。一个是大师,另一个是查阅。 TblMstr和Cmaster

Tblmstr

Id  QuestionId   ChoiceId ChoiceMaster
1    2             1       Strongly Agree
1    3             2       Disagree
1    4             3       Agree
1    5             11       null
2    2             2       Disagree
2    3             5       Disagree
2    4             9       Agree
2    5             12       null
克马斯特

ChoiceId  QuestionId    ChoiceName
1             2         Strongly Agree
2             2         Disagree
3             2         Agree
4             3         Strongly Agree
5             3         Disagree
6             3         Agree     
7             4         Strongly Agree
8             4         Disagree
9             4         Agree  
10            5         Registered Nurse
11            5         Nurse Practitioner
12            5         Pharmacist

我需要知道每个问题有多少注册护士强烈同意、不同意和同意。护士从业者和药剂师也是如此。

嗯。您可以加入两次。一次了解职业,一次了解其他问题的答案:

select co.choicename as occupation,
       sum(case when c.choicename = 'Strongly Agree' then 1 else 0 end) as cnt_strongly_agree,
       sum(case when c.choicename = 'Agree' then 1 else 0 end) as cnt_agree,
       sum(case when c.choicename = 'Disagree' then 1 else 0 end) as cnt_disagree
from Tblmstr m join
     Cmaster co
     on co.id = m.choiceid and co.questionid = 5 join
     Cmaster c
     on co.id = m.choiceid and co.questionid <> 5
group by co.choicename
选择co.choicename作为职业,
求和(c.choicename='Strongly Agree'然后1或0 end时的情况)为cnt_Strongly_Agree,
求和(当c.choicename='Agree'时,则为1,否则为0结束)为cnt_Agree,
求和(当c.choicename='discovere'然后1 else 0 end时的情况)作为cnt_discovere
从Tblmstr m join
克马斯特公司
在co.id=m.choiceid和co.questionid=5时加入
克马斯特c
关于co.id=m.choiceid和co.questionid 5
集团公司choicename