获取每一秒的总数(Postgres分层查询实践)
Accessing to total number in each second level(Postgres Hierarchical Query Practice)
我在 Postgres 上练习,卡在了一个我找不到实现方法的点上。我有一个简单的数据库,它是属性:
CREATE TABLE public.department
(
"deptId" integer NOT NULL PRIMARY KEY,
name character varying(30) COLLATE pg_catalog."default" NOT NULL,
"parentId" integer,
"numEmpl" integer NOT NULL,
CONSTRAINT "department_parentId_fkey" FOREIGN KEY ("parentId")
REFERENCES public.department ("deptId") MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
然后我在 table 中有一些数据。简短的例子是
insert into department values (1, 'Headquarter', 1, 10);
insert into department values (2, 'Sales', 1, 15);
insert into department values (3, 'Logistics', 1, 25);
...
我试图获得每个二级部门的雇员总数。
我能够获得每个部门的雇员总数,但根据我在互联网上的搜索,这可以通过“分层查询”实现。目前,我正在使用
parentId=1
正在查询。
有什么解决办法吗?谢谢。
这是一个选项:
with recursive cte as (
select deptid as rootid, deptid from department where parentid = 1 and deptid <> 1
union all
select c.rootid, d.deptid
from cte c
inner join department d on d.parentid = c.deptid and d.deptid <> 1
)
select rootid, count(*) cnt from cte group by rootid
我在 Postgres 上练习,卡在了一个我找不到实现方法的点上。我有一个简单的数据库,它是属性:
CREATE TABLE public.department
(
"deptId" integer NOT NULL PRIMARY KEY,
name character varying(30) COLLATE pg_catalog."default" NOT NULL,
"parentId" integer,
"numEmpl" integer NOT NULL,
CONSTRAINT "department_parentId_fkey" FOREIGN KEY ("parentId")
REFERENCES public.department ("deptId") MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
然后我在 table 中有一些数据。简短的例子是
insert into department values (1, 'Headquarter', 1, 10);
insert into department values (2, 'Sales', 1, 15);
insert into department values (3, 'Logistics', 1, 25);
...
我试图获得每个二级部门的雇员总数。
我能够获得每个部门的雇员总数,但根据我在互联网上的搜索,这可以通过“分层查询”实现。目前,我正在使用
parentId=1
正在查询。
有什么解决办法吗?谢谢。
这是一个选项:
with recursive cte as (
select deptid as rootid, deptid from department where parentid = 1 and deptid <> 1
union all
select c.rootid, d.deptid
from cte c
inner join department d on d.parentid = c.deptid and d.deptid <> 1
)
select rootid, count(*) cnt from cte group by rootid