SQL查询用于查找每个部门的子部门

时间:2013-08-14 06:49:49

标签: mysql sql subquery

我想写一个查询,它将返回部门名称及其子部门的相应数量。

我有以下表结构:

Table Name# Department
Dept_ID(Pk) Dept_name parent_dept_id(references dept_id)

虚拟数据将是

DEPT_ID            DEPT_NAME            PARENT_DEP_ID   
1              HEAD OFFICE               1
2              ADMINISTRATION            1
3              ARTS                      2
4              SCIENCE                   2
12             Agriculture               2
5              COMP. SCIENCE             4

我们将不胜感激。

4 个答案:

答案 0 :(得分:1)

<强> Here is the SQLFiddel Demo

以下是您可以尝试的查询

select P.DEPT_ID,P.DEPT_NAME,count(C.DEPT_ID)
  from Department P
  Left join Department C
    on p.DEPT_ID = C.PARENT_DEP_ID
   and p.DEPT_ID <> C.DEPT_ID
 group by P.DEPT_ID,P.DEPT_NAME

答案 1 :(得分:0)

你可以试试这个 -

Select count(*) as count, P.* from Department P 
  LEFT JOIN Department C ON p.dept_id = C.parent_dep_id
  GROUP BY C.parent_dep_id

答案 2 :(得分:0)

试试这个

select *,count(ChildDepart.PARENT_DEP_ID)    from Department as ParentDepart inner join
Department as ChildDepart in ParentDepart.DEPT_ID = ChildDepart.PARENT_DEP_ID

答案 3 :(得分:0)

select DEPT_ID,DEPT_NAME,coalesce(dt.child,0) CHILD 
from department d
left join
(
  select PARENT_DEP_ID,count(1) child 
  from department 
  where DEPT_ID <> PARENT_DEP_ID 
  group by 1
)dt
on d.DEPT_ID=dt.PARENT_DEP_ID;