计算每个学生的出勤率

时间:2018-03-28 01:18:20

标签: sql oracle

软件:PowerSchool(Oracle数据库)教育软件

当我为一名学生运行sql时,出勤率正确。当我添加额外学生时,计数将成为所有学生的总数,并列出每个学生的总数。如何在每个学生之后重置计数或将子查询放在不同的位置?任何建议赞赏。利兹〜

SELECT s.DCID,
s.lastfirst, 
(SELECT COUNT(distinct att.ID) 
                       FROM Students s JOIN Attendance att ON         
s.id=att.studentid
                      JOIN  Attendance_code attc ON         
attc.id=att.attendance_codeID
                        WHERE  s.id=att.studentid 
                     AND s.id=5538
                   AND att.Att_Mode_Code='ATT_ModeDaily'
                    AND att.yearid=27
                  AND attc.Presence_Status_CD = ('Absent')) AS TAbs
FROM Students s  

WHERE  s.enroll_tatus=0
AND s.grade_level IN (6, 7, 8)
 AND s.id=5538
ORDER BY s.grade_level ASC, s.lastfirst ASC;

2 个答案:

答案 0 :(得分:0)

您的查询应该是这样的:

SELECT s.DCID,
s.lastfirst, 
(SELECT COUNT(distinct att.ID) 
                       FROM Students s JOIN Attendance att ON         
s.id=att.studentid
                      JOIN  Attendance_code attc ON         
attc.id=att.attendance_codeID
                        WHERE  s.id=att.studentid 
                     AND s.id=5538
                   AND att.Att_Mode_Code='ATT_ModeDaily'
                    AND att.yearid=27
                  AND attc.Presence_Status_CD = ('Absent')) AS TAbs
FROM Students s  

WHERE  s.enroll_tatus=0
AND s.grade_level IN (6, 7, 8)
 AND s.id=5538
GROUP BY s.DCID, s.lastfirst #You should add this line
ORDER BY s.grade_level ASC, s.lastfirst ASC;

答案 1 :(得分:0)

你应该改变3件事:

  • 删除学生的ID过滤器。您希望查看所有学生,而不仅仅是ID 5538

  • 为同一个表使用不同的别名!您正在引用Students表两次,并且两次都使用相同的别名(S)。

  • 将最外面的StudentID与子查询StudentID相关联,因此每个COUNT(DISTINCT att.ID)都是由学生计算的,而不是整体

以下是已编辑的查询:

SELECT 
    s1.DCID,
    s1.lastfirst, 
    (
        SELECT 
            COUNT(distinct att.ID) 
        FROM 
            Students s2 -- Use different alias!
            JOIN Attendance att ON s2.id=att.studentid
            JOIN  Attendance_code attc ON attc.id=att.attendance_codeID
        WHERE  
            att.Att_Mode_Code='ATT_ModeDaily' AND 
            att.yearid=27 AND 
            attc.Presence_Status_CD = ('Absent') AND
            s1.id = s2.id -- Relate both Student tables
    ) AS TAbs
FROM 
    Students s1  
WHERE  
    s1.enroll_tatus=0 AND 
    s1.grade_level IN (6, 7, 8) 
ORDER BY 
    s1.grade_level ASC, 
    s1.lastfirst ASC;