Oracle SQL查询计数不同的分支

时间:2018-03-08 02:29:46

标签: sql oracle11g

我想要做的是了解拥有mgr并且没有mgr的员工数量。表格如下:

Emp     Branch   Mgr   
EmpA    Branch1  Mgr1  
EmpB    Branch2  Mgr2
EmpC    Branch1  Mgr2
EmpD    Branch1  
EmpE    Branch2  Mgr2
EmpF    Branch1  Mgr2

我想要的输出是这样的:

Branch     HasMgr HasNoMgr
Branch1    3      1
Branch2    2      0

已经尝试过此代码,但结果错误

SELECT branches,
(SELECT COUNT(*) FROM tbl WHERE mgr IS NULL),
(SELECT COUNT(*) FROM tbl WHERE mgr IS NOT NULL )
FROM tbl GROUP BY branches

3 个答案:

答案 0 :(得分:1)

使用子查询来总结具有/不具有值的所有经理。希望这可以帮助。感谢。

SELECT branch,
SUM(case when Mgr is not null then 1 else 0 end) hasmgr,
SUM(case when Mgr is not null then 0 else 1 end) hasnomgr
FROM tbl
GROUP by branch;

答案 1 :(得分:1)

With dat as(
Select 'Emp' emp   ,  'Branch' Branch, 'Mgr' as manager  UNION ALL
Select 'EmpA' ,   'Branch1',  'Mgr1'  union all
Select 'EmpB' ,   'Branch2',  'Mgr2' union all
Select 'EmpC' ,  'Branch1' , 'Mgr2' union all
Select 'EmpD' ,   'Branch1'  , null union all
Select 'EmpE'  ,  'Branch2' ,'Mgr2' union all
Select 'EmpF' ,   'Branch1' , 'Mgr2'
)
SELECT Branch,count(manager) hasMgr,sum(case when manager is null then 1 
else 0 end) hasNoMgr FROM dat
group by branch

答案 2 :(得分:0)

选择分支,     sum(decode(mgr,null,0,1))as" hasmgr",     sum(decode(mgr,null,1,0))as" hasnomgr"   来自TAB1   GROUP BY BRANCH