在单个列上执行两个COUNT而不在一个sql语句或pl / sql块中使用视图

时间:2014-04-16 16:39:13

标签: sql oracle plsql

我有一个有列的表出席 date1,status(PRESENT或ABSENT),student_idstudent和student_subject_subjectid

我想查询student_idstudent和他们拥有的百分比出勤率,即每个学生对于特定主题的出勤率(当前/总计数)。 基本上我只想要两个值的值。有没有简单的方法可以不使用视图,最好使用pl / sql?

下面是我尝试使用光标。

  • 请告诉我使用以下代码是否保证为每个student_idstudent提供相应的答案(即现在的计数和总数)
  • 还告诉我,在其他情况下是否会失败?

        DECLARE 
        s_id attendance.student_idstudent%type; 
        s_present number(3); 
        CURSOR student_present is select student_idstudent, count(student_idstudent) from  attendance 
        where status like 'Present' and student_subject_subjectid like 102 
        group by student_idstudent;
    
        s1_id attendence.student_idstudent%type; 
        s1_total number(3); 
        CURSOR student_total is select student_idstudent, count(student_idstudent) from attendance 
        where student_subject_subjectid like 102 
        group by student_idstudent;
    
        BEGIN 
        OPEN student_present; 
        OPEN student_total;
        LOOP 
        FETCH student_present into s_id, s_present;
        FETCH student_total into s1_id, s1_total;
        EXIT WHEN student_present%notfound;  
        dbms_output.put_line('student '|| s_id || ' has ' ||S_present/s1_total*100 || '% record' ); 
        END LOOP; 
    
        CLOSE student_present; 
        CLOSE student_total; 
        END; 
        /
    
  • 2 个答案:

    答案 0 :(得分:2)

    我不确定这是否是一个家庭作业问题,所以我给你一个部分答案,你应该能够自己完成查询。

    select student_idstudent
          ,count(case when status like 'Absent'  then 1 end) as absent_count
          ,count(case when status like 'Present' then 1 end) as present_count
          ,count(*)                                      as tot_count
      from attendance
     where student_subject_subjectid = 102
     group 
        by student_idstudent;
    

    此外,使用不带任何外卡字符的LIKE等同于使用=。为清楚起见,条件应该写为status = 'Absent'status = 'Present'。这也更清楚了。

    like <number>也是如此。您的意思是student_subject_subjectid = 102,还是您还有其他想法?

    答案 1 :(得分:0)

    随着@ronnis的帮助。
    我想出了这个答案。

        SELECT student_idstudent,
        count(CASE WHEN  status = 'Present'  then 1 END)/count(*)*100 as percentage
        FROM attendence 
        where student_subject_subjectid = 102
        group by student_idstudent;