试图找到多个级别的所有成员到许多关系,也是层次结构中最重要的成员 Multiple学生可以去1名老师,但是1名学生不能去找多个老师。这个教师学生层次结构没有级别的限制。 如何在SQL Server中使用单个SQL查询,我们可以得到...

问题描述 投票:0回答:1

toflow是预期的输出,提供了所选输入的位置

表和数据脚本快速参考table data

由于您的“链接的学生老师ID”对于给定校长的每个学生都是相同的,您可能需要每位校长一次计算该清单(而不是像您有学生一样多次计算它)。

然后a

common表expressionexpected output for input in where clause将允许您:

写入查询零件逐步
sql sql-server hierarchy hierarchical-data
1个回答
1
投票

…和使用递归

从数据库的角度来看,这只是一个查询(思考“依次依次书面”)。 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您要寻找的确切结果。

    thanks。但是,在尝试从5亿张桌子上获得单个sudentingId(例如25)时,花了太多时间。似乎所有的层次结构都是由5亿行建立的,然后是学生ID的记录(例如25)。可以在查询中以滤波器作为过滤器引入该studentId = 25,以便查询计划是最佳的,并且仅获取对应于25的hierachy。
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.