sql计算出现和缺席的男孩和女孩

时间:2016-05-22 12:24:22

标签: php mysql sql

无法提出正确的查询来计算学生总人数

我有三张桌子:

  1. 学生 - 包含男性或女性的学生档案
  2. 2.student_attendance - 包含学生是否在场的出勤细节" 0"或" 1"

    1. 出勤 - 包含所有会议详情,其中一个学生可以参加一个课程。
    2. 我需要计算一个会议现在或缺席的男孩/女孩的数量。

      我的主要问题是将这些逻辑解释为sql

      if(in_attendace =1) then 
          sum the number of boys as boys_present
          sum the number of girls as girls_present
      else
          sum the number of boys as boys_absent
          sum the number of girls as girls_absent
      
      #我最近的sql是它无法正常工作:(
      select 
      case when a.in_attendance = 1 then
      SUM(CASE b.gender when 1 then 1 else 0 end ) as male_present,
      SUM(CASE b.gender when 2 then 1 else 0 end ) as female_present,
      ELSE
      SUM(CASE b.gender when 1 then 1 else 0 end ) as male_absent,
      SUM(CASE b.gender when 2 then 1 else 0 end ) as female_absent
      END
      from attendance_student  as a inner join student as b on a.student_id = b.id where a.session_details_id = 38
      

1 个答案:

答案 0 :(得分:2)

嗯,你离解决方案不是很远,你只需要将它们分成不同的列(我认为这就是你想要的):

select COUNT(CASE WHEN a.in_attendance = 1 and b.gender = 1 then 1 END) as male_present,
       COUNT(CASE WHEN a.in_attendance = 1 and b.gender = 2 then 1 END) as female_present,
       COUNT(CASE WHEN a.in_attendance = 0 and b.gender = 1 then 1 END) as male_absent,
       COUNT(CASE WHEN a.in_attendance = 0 and b.gender = 2 then 1 END) as female_absent
FROM attendance_student a
INNER JOIN student b
 ON a.student_id = b.id 
WHERE a.session_details_id = 38