PostgreSQL递归和+路径

时间:2019-07-16 10:12:01

标签: sql postgresql common-table-expression recursive-query

我是递归查询的新手。

我有两个表:

  • m_unit具有层次结构
  • m_employee

这是示例数据

create table m_unit(
 unit_id integer primary key,
 unit_name varchar(100) not null,
 parent_id integer references m_unit(unit_id)
 );

INSERT INTO m_unit(
 unit_id,unit_name, parent_id)
VALUES 
( 1,'Epam', null),
( 2,'Epam1', 1),
( 3,'Epam2', 1),
( 4,'Epam3', 2),
( 5,'Epam4', 4),
( 6,'Epam5', 3);

create table m_employee(
  employee_id integer primary key,
  employee_name varchar(100) not null,
  unit_id integer references m_unit(unit_id)
);

INSERT INTO m_employee(
  employee_id,employee_name, unit_id)
VALUES 
( 1,'Emp1', 1),
( 2,'Emp2', 1),
( 3,'Emp3', 2),
( 4,'Emp4', 3),
( 5,'Emp5', 2),
( 6,'Emp6', 4),
( 7,'Epm7', 3),
( 8,'Epm8', 2),
( 9,'Epm9', 6),
( 10,'Epm10', 1);

我需要获取unit_id,unit_name,path,employeeCount,сountEmplIncludChildUnit

类似的东西

unit_Id  unit_name   path             countEmployee сountEmplIncludChildUnit
1       "Epam"      "Epam"              3               10
2       "Epam1"     "Epam/Epam1"        3               4
3       "Epam2"     "Epam/Epam2"        2               3
4       "Epam3"     "Epam/Epam1/Epam3"  1               1
6       "Epam5"     "Epam/Epam2/Epam5"  1               1

我写了一个查询,但是上一栏сountEmplIncludChildUnit有点麻烦 我需要帮助

with recursive subord as (
    select unit_id, unit_name, cast(unit_name as varchar(1000)) as path 
    from m_unit 
    where parent_id is null
    union all
    select m.unit_id,m.unit_name,cast(concat_ws('/',s.path,m.unit_name) as varchar(1000)) 
    from m_unit m
      inner join subord s on s.unit_id = m.parent_id
)
select s.unit_id,s.unit_name,s.path,count(empl.employee_id) as employeeCount 
from subord s
    join m_employee empl on
    s.unit_id = empl.unit_id
group by s.unit_id,s.unit_name,s.path
order by unit_id

感谢帮助

0 个答案:

没有答案