toflow是预期的输出,提供了所选输入的位置
由于您的“链接的学生老师ID”对于给定校长的每个学生都是相同的,您可能需要每位校长一次计算该清单(而不是像您有学生一样多次计算它)。
然后acommon表expression将允许您:
写入查询零件逐步
…和使用递归
从数据库的角度来看,这只是一个查询(思考“依次依次书面”)。
with
-- h (Hierarchy) is computed recursively. Each step gets its level (which will help order the groups later)
h as
(
-- Head teachers are those who are not student either.
select distinct TeacherId as id, TeacherId as HeadTeacherId, 0 hlevel from t where not exists (select 1 from t UberTeacher where t.TeacherId = UberTeacher.StudentId)
union all
select StudentId, HeadTeacherId, hlevel + 1
from h join t on t.TeacherId = h.id
),
-- Now compute the whole group only once per head teacher.
heads as
(
select HeadTeacherId id, string_agg(id, ',') within group (order by hlevel desc, id desc) WholeGroup
from h
group by HeadTeacherId
)
-- Finally each student gets a copy of its head teacher's list.
select h.id, HeadTeacherId, WholeGroup
from h join heads on h.HeadTeacherId = heads.id;
thistive this thives您要寻找的确切结果。