sql - 两次加入一个表并计算记录
问题描述
我有 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
我需要让每个问题有多少注册护士有强烈同意、不同意和同意。对于执业护士和药剂师也是如此。
解决方案
嗯。. . 你可以join
两次。一次获得职业,一次获得其他问题的答复:
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
推荐阅读
- python - 使用 boto3 更新 DynamoDb
- reactjs - 如何将非受控组件移动到受控组件
- python - 如何从 python 将中文字体打印到 Zebra ZPL 打印机?
- javascript - JavaScript中Reflect.get方法的第三个参数的目的是什么
- c++ - 布尔函数返回问题
- javascript - JSDoc - 是否可以制作一个集成的 html 文档?
- android - 当我在 Android 中使用 Room 时,如何简单地通过传递参数来进行查询
- powershell - 有没有办法只获得驱动器上的可用空间?
- javascript - GitHub API v3:创建问题时出现 404 错误
- node.js - Node.js/Electron - 我可以重置系统空闲时间吗?