在一个查询中获取总计数和总不存在数

时间:2015-03-31 05:20:23

标签: mysql join

我有两张桌子学生和出勤。我需要加入两个表并获得结果,如总缺席数和特定类和类名的学生数。我需要一个查询来获得以下结果

tbl_student:

admission_no(PK)          student_name        student_class
345                           John                 X A
352                           Sachin               X A
322                           Steve                IX A
123                           Pinky                X A
343                           Rose                 IX A

tbl_admission:

admission_no(FK)             date_absent
354                          2015-03-30
123                          2015-03-30
322                          2015-03-30

结果应该是这样的:

 Date_absent        total_absent        total_students      student_class
 2015-03-30            2                    3                  X A
 2015-03-30            1                    2                  IX A

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情来在单一查询中管理它:

SELECT date_absent, total_absent, total_students, a1.student_class
FROM (
  SELECT date_absent, count( tbl_admission.admission_no ) AS total_absent, tbl_student.student_class
  FROM `tbl_admission`
  JOIN `tbl_student` ON tbl_student.admission_no = tbl_admission.admission_no
  GROUP BY tbl_student.student_class
)a1
JOIN (
  SELECT count( tbl_student.admission_no ) AS total_students, tbl_student.student_class
  FROM tbl_student
  GROUP BY tbl_student.student_class
)a2
ON a1.student_class = a2.student_class
ORDER BY `a1`.`student_class` DESC