我有一个名为employee的表,如下所示:
emp dept
---- ----
1 HR
2 Accounts
3 HR
4 Dev
2 Dev
员工可能属于多个部门,例如,员工2。
我想要这样的输出:
dept empInDept totalCountofEmp
----- --------- ----------------
HR 2 4
Accounts 1 4
我可以得到如下所示的特定部门的雇员人数:
select dept,count(*) as empInDept from employees where dept ='HR' or dept='Accounts' group by dept
但是我不确定是否可以创建一个单个查询,在该查询中可以得到上述select
查询的结果,并由此获得员工的整体数量桌子。
答案 0 :(得分:1)
以下是您的请求示例:
create table #temp
(id int, value int)
insert into #temp values (1,2),(2,3),(1,5)
select id, count(Value), (select count(distinct value) from #temp) as X
from #temp
group by id
对于您的特定任务,请尝试以下操作:
select dept,
count(*) as empInDept
(select count(distinct emp) from employees) as TotalCount
from employees where dept ='HR' or dept='Accounts'
group by dept
答案 1 :(得分:0)
您可以使用ANSI / ISO标准rollup
或grouping sets
:
select dept, count(distinct emp)
from employees
where dept in ('HR', 'Accounts')
group by grouping sets (dept, ());
更多数据库支持rollup
,但是语法可能有所不同。一种方法是:
select dept, count(distinct emp)
from employees
where dept in ('HR', 'Accounts')
group by rollup(dept);