SQL 26) 汇总各个部门当前员工的title类型的分配数目
汇总各个部门当前员工的title类型的分配数目
http://www.nowcoder.com/questionTerminal/4bcb6a7d3e39423291d2f7bdbbff87f8
方法)三表连结分组
SELECT d.dept_no, d.dept_name, t.title, COUNT(t.emp_no) FROM departments AS d, dept_emp AS de, titles AS t WHERE d.dept_no = de.dept_no AND t.emp_no = de.emp_no AND de.to_date = '9999-01-01' AND t.to_date = '9999-01-01' GROUP BY d.dept_no, d.dept_name, t.title ORDER BY d.dept_no;
21/3/25 更新
方法2)简化代码,用窗口函数count()over()解决
select distinct d.dept_no, d.dept_name, t.title, count(t.emp_no)over(partition by t.title , de.dept_no) from departments as d join dept_emp as de on d.dept_no = de.dept_no join titles as t on t.emp_no = de.emp_no where de.to_date = '9999-01-01' and t.to_date = '9999-01-01' order by d.dept_no;
SQL 文章被收录于专栏
SQL