划分两个查询以获得每个学期的通过率

时间:2017-04-14 03:01:18

标签: sql

我正在尝试为表格编写查询,我希望确定一个学期的通过率是多少。

第一个查询(QUERY 1)将向我提供一个学期中通过的学生数量,第二个查询(QUERY 2)将为我提供一个学期中代码= 4897的特定主题的学生总数。 / p>

我需要执行计算(QUERY 1 / QUERY 2)并按学期代码显示结果。

QUERY 1:

 select count(c.student) as q1, s.semester
 from course_enrolments c join courses s on c.course = s.id
 where s.subject = 4897 and mark >= 50
 group by s.semester;

QUERY 2:

 select count(c.student) as q2, s.semester
 from course_enrolments c join courses s on c.course = s.id
 where s.subject = 4897
 group by s.semester;
  

然后q1 / q2 =

结果应该是这样的:

semester | pass_rate | 
------+--------------+
    03   |      1.00 |         
    04   |      1.00 |        
    05   |      1.00 |         
    06   |      1.00 |        
    07   |      1.00 |         
    08   |      0.81 |    
    09   |      0.89 |         

1 个答案:

答案 0 :(得分:0)

使用条件聚合:

select s.semester,
       count(*) as num_students,
       sum(case when mark >= 50 then 1 else 0 end) as passes,
       avg(case when mark >= 50 then 1.0 else 0 end) as pass_rate,
from course_enrolments c join
     courses s
     on c.course = s.id
where s.subject = 4897 and mark >= 50
group by s.semester;