繁体   English   中英

SQL表-根据其他2个表的条件对table1的行进行计数

[英]SQL Tables - Count rows of table1 based on other 2 tables' conditions

我的问题是我想计算n个系下的所有学生。
注意:学生拥有一门课程,并且课程有其所属部门(1个部门中有许多课程)。 样品输出:

+---------+-------------------------------+
| student | department                    |
+---------+-------------------------------+
|       23| Computer Education Department |
|       67| Basic Education Department    |
|       39| Mathematics Department        |
|       40| Humanities Department         |
|       61| Engineering Department        |
|       79| Management Department         |
+---------+-------------------------------+
  1. tbl_students
+---------+---------------+--------+
| 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         |
+---------+-------------------------------+

我认为您可以执行以下操作:

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 
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

我希望它对您有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM