【问题标题】:SQL Tables - Count rows of table1 based on other 2 tables' conditionsSQL 表 - 根据其他 2 个表的条件计算表 1 的行数
【发布时间】:2017-11-14 21:44:45
【问题描述】:

我的问题是我想计算 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
+---------+---------------+--------+
|螺柱ID |姓名 |课程 |
+---------+---------------+--------+
| 1 |杰克欧文 | 1 |
| 2 |柯比洛佩兹 | 2 |
| 3 |贾斯汀减 | 1 |
| 4 |杰罗姆·诺维达 | 1 |
+---------+---------------+--------+

2. tbl_courses

+-----------+------------+---------+
| course_id |短名 |部门 ID |
+-----------+------------+---------+
| 1 |基础设施 | 1 |
| 2 |理学士 | 1 |
| 3 | BEED | 2 |
| 4 | BSED | 2 |
| 6 | BSTHRM | 7 |
| 7 |幸福感 | 4 |
| 8 |理学士 | 6 |
+-----------+------------+---------+

3. tbl_department

+---------+-------------------+
|部门 ID |全名 |
+---------+------------------+
| 1 |计算机教育系 |
| 2 |基础教育部 |
| 3 |数学系 |
| 4 |人文系 |
| 6 |工程系 |
| 7 |管理部 |
+---------+------------------+

【问题讨论】:

  • 这看起来像家庭作业。你有没有自己尝试过解决问题?
  • 你试过JOIN语句吗?
  • 是的,我尝试加入这 3 个表,但我无法找出符合我想要的正确条件。我尝试了连接表的 ANSI 方法和旧方法(只需选择 3 个表),但我无法弄清楚。顺便说一句,这不是我正在处理自己的项目的作业,我遇到了这个问题。
  • @MuTiny 是的,但我无法确定正确的条件。
  • 第一个,MySQL 和 SQL-Serveur 标签.. 你在使用女巫吗? stackoverflow.com/documentation/sql-server/1008/…

标签: mysql sql-server database jointable


【解决方案1】:

我认为你可以这样做:

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 

【讨论】:

  • 这就是我所需要的。
【解决方案2】:
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

我希望它对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 2020-09-21
    相关资源
    最近更新 更多