580. 在 Leetcode 上计算部门中的学生人数

580. Count Student Number in Departments on Leetcode

我使用 SQL 服务器来解决这个问题

输入: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

输出:

dept_name   student_number
---------------------------
Engineering  2
Science      1
Law          0
SELECT 
    d.dept_name,
    COUNT(s.student_id) OVER(PARTITION BY d.dept_name) AS student_number
FROM 
    Department AS d
LEFT JOIN 
    Student AS s ON d.dept_id = s.dept_id
ORDER BY 
    student_number DESC, d.dept_name; 

不过,我得到了

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


dept_id student_number
-----------------------
   1        2
   1        2
   2        1
   3        0

DISTINCT() 可以解决这个问题,但我不明白为什么我们需要对不同的值使用 DISTINCT()。谁能帮忙解释一下?谢谢

SELECT DISTINCT 
    d.dept_name,
    COUNT(s.student_id) OVER(PARTITION BY d.dept_name) AS student_number
FROM
    Department AS d
LEFT JOIN 
    Student AS s ON d.dept_id = s.dept_id
ORDER BY 
    student_number DESC, d.dept_name;

只需左连接两个表,然后使用 COUNT 作为聚合函数,而不是分析函数。

SELECT
    d.dept_id,
    d.dept_name,
    COUNT(s.student_id) AS student_number
FROM Department d
LEFT JOIN Student s
    ON s.dept_id = d.dept_id
GROUP BY
    d.dept_id,
    d.dept_name;

如果我们使用 left join,则不会考虑法学院学生的人数,但正如问题中所述,对于这种情况,我们需要显示 0。

select
     d.dept_name,count(s.student_id) as student_number 
from  
     Student s right join Department d
on
     s.dept_id = d.dept_id
group by 
     d.dept_id
order by
     student_number desc,dept_name