查找树结构中的所有成员

时间:2016-11-16 11:40:03

标签: sql sql-server

我以这种格式继承了一个树型表

<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <style is="custom-style">
    .flexcol {
      --x-foo-flex-direction: row;
    }
  </style>
  <x-foo></x-foo>
  <x-foo class="flexcol"></x-foo>
  
  <dom-module id="x-foo">
    <template>
      <style>
        :host {
          display: flex;
          flex-direction: var(--x-foo-flex-direction, column);
        }
      </style>
      <div>a</div>
      <div>b</div>
      <div>c</div>
    </template>
    <script>
      HTMLImports.whenReady(() => {
        Polymer({
          is: 'x-foo'
        });
      });
    </script>
  </dom-module>
</body>

我想找到最终父母主题所在的所有StatementAreaIds,比如数学(即SubjectId = 110)。例如,如果SubjectId是Maths,我会在树中获得StatementAreaIds列表:

StatementAreaId | ParentStatementAreaId | SubjectId | Description
-----------------------------------------------------------------
1               | 0                     | 100       | Reading
2               | 0                     | 110       | Maths
3               | 2                     | 0         | Number
4               | 2                     | 0         | Shape
5               | 3                     | 0         | Addition
6               | 3                     | 0         | Subtraction

如果有帮助,树的最大深度为3。

由于

1 个答案:

答案 0 :(得分:2)

拯救的递归CTE:

创建并填充样本表:(在将来的问题中将此步骤保存起来)

SslMode=None

查询:

DECLARE @T AS TABLE
(
    StatementAreaId int,
    ParentStatementAreaId int, 
    SubjectId int,
    Description varchar(20)
)

INSERT INTO @T VALUES
(1               , 0                     , 100       , 'Reading'),
(2               , 0                     , 110       , 'Maths'),
(3               , 2                     , 0         , 'Number'),
(4               , 2                     , 0         , 'Shape'),
(5               , 3                     , 0         , 'Addition'),
(6               , 3                     , 0         , 'Subtraction')

结果:

;WITH CTE AS 
(
    SELECT StatementAreaId, ParentStatementAreaId
    FROM @T 
    WHERE SubjectId = 110

    UNION ALL
    SELECT t1.StatementAreaId, t1.ParentStatementAreaId
    FROM @T t1 
    INNER JOIN CTE ON t1.ParentStatementAreaId = CTE.StatementAreaId
)

SELECT StatementAreaId
FROM CTE