根据性别和得分百分比从多个表格中获取计数

时间:2019-03-15 13:17:58

标签: sql sql-server

我必须使用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 个答案:

答案 0 :(得分:1)

您可以尝试在表达式出现时使用常规聚合

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