返回介绍

solution / 0500-0599 / 0580.Count Student Number in Departments / README_EN

发布于 2024-06-17 01:03:59 字数 3307 浏览 0 评论 0 收藏 0

580. Count Student Number in Departments

中文文档

Description

Table: Student

+--------------+---------+
| Column Name  | Type  |
+--------------+---------+
| student_id   | int   |
| student_name | varchar |
| gender     | varchar |
| dept_id    | int   |
+--------------+---------+
student_id is the primary key (column with unique values) for this table.
dept_id is a foreign key (reference column) to dept_id in the Department tables.
Each row of this table indicates the name of a student, their gender, and the id of their department.

 

Table: Department

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| dept_id   | int   |
| dept_name   | varchar |
+-------------+---------+
dept_id is the primary key (column with unique values) for this table.
Each row of this table contains the id and the name of a department.

 

Write a solution to report the respective department name and number of students majoring in each department for all departments in the Department table (even ones with no current students).

Return the result table ordered by student_number in descending order. In case of a tie, order them by dept_name alphabetically.

The result format is in the following example.

 

Example 1:

Input: 
Student table:
+------------+--------------+--------+---------+
| student_id | student_name | gender | dept_id |
+------------+--------------+--------+---------+
| 1      | Jack     | M    | 1     |
| 2      | Jane     | F    | 1     |
| 3      | Mark     | M    | 2     |
+------------+--------------+--------+---------+
Department table:
+---------+-------------+
| dept_id | dept_name   |
+---------+-------------+
| 1     | Engineering |
| 2     | Science   |
| 3     | Law     |
+---------+-------------+
Output: 
+-------------+----------------+
| dept_name   | student_number |
+-------------+----------------+
| Engineering | 2        |
| Science   | 1        |
| Law     | 0        |
+-------------+----------------+

Solutions

Solution 1: Left Join + Grouping

We can use a left join to join the Department table and the Student table on dept_id, and then group by dept_id to count the number of students in each department. Finally, we can sort the result by student_number in descending order and dept_name in ascending order.

# Write your MySQL query statement below
SELECT dept_name, COUNT(student_id) AS student_number
FROM
  Department
  LEFT JOIN Student USING (dept_id)
GROUP BY dept_id
ORDER BY 2 DESC, 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文