我有两张包含员工和部门信息的表格。两者看起来如下
员工表:
ID_emp ID_dep year
3000 4 0
3001 4 1
3002 4 2
3003 16 3
3004 15 3
部门表:
ID_dep dep_descr
16 management
4 accounting
现在,我需要找出每个部门雇用超过1年的员工人数,并提供每个部门的员工百分比,相对于雇员超过1年的员工总数。整个公司(所有部门)。
结果应如下所示:
dep_descr number of employees percent of total employees
management 12 5%
accounting 4 1.6%
... ... ...
答案 0 :(得分:1)
这个怎么样?
select
concat(cast(count(e.id_emp)/(select count(id_emp) from employee) * 100 as decimal(4,2)), '%') employees_in_dept, d.dep_descr
from employee e
inner join department d
on e.id_dep = d.id_dep
group by d.id_dep
答案 1 :(得分:0)
create temp table emp (id_emp int, id_dep int, nyear int);
create temp table dep (id_dep int, desc_dep text);
insert into dep values (16,'management'),(4, 'accounting');
insert into emp values (3000,4,0),(3001,4,1),(3002,4,2),(3003,16,3),(3004,16,3);
with cte (id_dep, desc_dep, num_employees) as
(
select emp.id_dep, dep.desc_dep, count(*)
from emp
left join dep on emp.id_dep = dep.id_dep
where emp.nyear > 1
group by emp.id_dep, dep.desc_dep
)
select
cte.id_dep,
cte.desc_dep,
cte.num_employees,
cte.num_employees * 100 / (select count(*) from emp where emp.nyear > 1)::float as percent_of_total
from cte;
答案 2 :(得分:-1)
到目前为止你尝试了什么?您可能需要使用子查询来计算员工总数,并将其用于划分由部门分组的员工数。