我的问题是我想要算上 n 部门下的所有学生。
注意:学生有一门课程,课程有自己的部门(一个部门有很多课程)。 样品输出:
+---------+-------------------------------+
| student | department |
+---------+-------------------------------+
| 23| Computer Education Department |
| 67| Basic Education Department |
| 39| Mathematics Department |
| 40| Humanities Department |
| 61| Engineering Department |
| 79| Management Department |
+---------+-------------------------------+
+---------+---------------+--------+ | stud_id | name | course | +---------+---------------+--------+ | 1 | Jack Owen | 1 | | 2 | Kirby Lopez | 2 | | 3 | Justin Minus | 1 | | 4 | Jerome Noveda | 1 | +---------+---------------+--------+
2。 tbl_courses
+-----------+------------+---------+ | course_id | short_name | dept_id | +-----------+------------+---------+ | 1 | BSIT | 1 | | 2 | BSCS | 1 | | 3 | BEED | 2 | | 4 | BSED | 2 | | 6 | BSTHRM | 7 | | 7 | BLIS | 4 | | 8 | BSCE | 6 | +-----------+------------+---------+
3。 tbl_department
+---------+-------------------------------+ | dept_id | full_name | +---------+-------------------------------+ | 1 | Computer Education Department | | 2 | Basic Education Department | | 3 | Mathematics Department | | 4 | Humanities Department | | 6 | Engineering Department | | 7 | Management Department | +---------+-------------------------------+
答案 0 :(得分:0)
我认为你可以这样做:
SELECT
tbl_department.full_name as department,
COUNT(DISTINCT tbl_students.stud_id) AS student
FROM
tbl_department
JOIN tbl_courses
ON tbl_department.dept_id = tbl_courses.dept_id
JOIN tbl_students
ON tbl_courses.course_id = tbl_students.course
GROUP BY
tbl_department.full_name
答案 1 :(得分:0)
SELECT
ISNULL(( SELECT COUNT(*) FROM tbl_courses C
INNER JOIN tbl_students S ON C.course_id = S.course
WHERE C.dept_id = D.dept_id
),0) AS student
,D.full_name AS department
FROM
tbl_department D
我希望它对你有用。