根据性别和得分百分比从多个表格中获取计数
Posted
技术标签:
【中文标题】根据性别和得分百分比从多个表格中获取计数【英文标题】:getting count from multiple tables on the basis of gender and scored percentages 【发布时间】:2019-03-15 13:17:58 【问题描述】:我必须使用 3 张桌子
1. tbl_school_info
school_id school_name
1 St. Joseph
2 White Cross
2. tbl_student_info
student_id school_id student_name student_gender
1 1 maria liejal F
2 1 eerika carthy F
3 1 heron M
4 2 Glenn hui M
5 2 joseph M
6 2 christii F
7 2 hina moggy F
3. tbl_student_marks
marks_id school_id student_id scored_percentage
1 1 1 78
2 1 2 79
3 1 3 20
4 2 4 65
5 2 5 78
6 2 6 84
7 2 7 83
我需要的结果是每所学校的男性、女性和总学生人数、男性女性通过学生人数和得分最高的男性女性学生。结果会是这样::
school_name || male_stud_cnt || female_stud_cnt || passed_male_cnt || passed_female_cnt || top_percentage_male ||top_percentage_female
St. Joseph 1 2 0 2 20 79
White Cross 2 2 2 2 78 84
分数低于 35% 的学生未通过考试。如何编写查询以获得此结果?是否可以在 MS SQL Server 中使用 SQL 查询获得这样的结果?我无法获得计数,我该如何编写这样的查询?
【问题讨论】:
如果这是学校作业,你能展示一下你尝试了什么吗? 【参考方案1】:您可以尝试使用带有 case when 表达式的条件聚合
with cte as
(
select school_name,a.student_id,student_gender,scored_percentage from
tbl_student_marks a inner join tbl_student_info b
on a.student_id=b.student_id
inner join tbl_school_info c on a.school_id=b.school_id
)
select school_name,
count(case when student_gender='M' then student_id end) as male_stud_cnt,
count(case when student_gender='F' then student_id end) as female_stud_cnt,
count(case when student_gender='M' and scored_percentage>35 then student_id end) as passed_male_cnt,
count(case when student_gender='F' and scored_percentage>35 then student_id end) as passed_female_cnt,
max(case when student_gender='M' then scored_percentage end) as top_percentage_male,
max(case when student_gender='F' then scored_percentage end) as top_percentage_female
from cte
group by school_name
【讨论】:
以上是关于根据性别和得分百分比从多个表格中获取计数的主要内容,如果未能解决你的问题,请参考以下文章