leetcode580. Statistics Number of all students (SQL)

A university has two data tables, which are student and department, holds two tables of data for each student and faculty data.

Write a query, the query number of professional department table each student (even in the absence of professional students also need to list).

Your query results in descending order according to the number of students. If there are two or more professional to have the same number of students, these sectors will be in ascending order according to the dictionary order department name.

student the following table:

| Column the Name | Type |
| -------------- | ----------- |
| student_id | Integer |
| student_name | String |
| Gender | Character |
| dept_id | Integer |
which, student_id is the student's school number, student_name is the student's name, gender, gender students, dept_id their profession professional student numbers.

department the following table:

| Column the Name | Type |
| ------------- | --------- |
| dept_id | Integer |
| dept_name | String |
dept_id professional number, dept_name professional name .

Here is an example of an input:
Student table:

| student_id | student_name | gender | dept_id |
|------------|--------------|--------|---------|
| 1          | Jack         | M      | 1       |
| 2          | Jane         | F      | 1       |
| 3          | Mark         | M      | 2       |
department 表格:

| The dept_id | dept_name, |
| --------- | ------------- |
|. 1 | Engineering |
| 2 | Science |
|. 3 | Law |
exemplary output:

| dept_name   | student_number |
|-------------|----------------|
| Engineering | 2              |
| Science     | 1              |
| Law         | 0              |

Ideas: a nested query the number of each professional learning, then sort.

select a.dept_name as 'dept_name',(select count(*) from student as b where b.dept_id=a.dept_id) as 'student_number'
from department as a
order by student_number desc,dept_name;

 

发布了583 篇原创文章 · 获赞 1万+ · 访问量 138万+

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104389898