2016-12-07 58 views
-1

我有兩個表包含員工和部門的信息。這兩個看起來如下MySQL的計數值,並獲得在一個SQL查詢的百分比

Employee表:

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% 
...    ...      ... 

回答

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

我已經嘗試使用count()和groupby()一起使用。我設法達到了一個表格,該表格顯示了每個部門的員工數量,但是包含百分比值的每次嘗試都會導致錯誤:S – AaronDT

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;