从具有级别路径的表生成父子层次结构

时间:2016-03-18 14:30:34

标签: sql tsql parent-child hierarchy

我设法在这样的表中转换了一些不可读的数据。 SQL表表示多层平面层次结构。问题是,如何根据下面的级别和结构生成一个普通的参差不齐的sql parent-child层次结构:ID | Element | Parent

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用层次结构和自动递增ID创建一个新表,如下所示:

create table hierarchy (
  id int not null identity (1,1) primary key,
  element varchar(100),
  parent int
);

然后你会先将1级元素添加到它,因为它们没有父级:

insert into hierarchy (element, parent)
  select     distinct f.level1, null
  from       flat f;

现在您已为这些元素生成 id 值,您可以添加下一个级别,如下所示:

insert into hierarchy (element, parent)
  select     distinct f.level2, h1.id
  from       hierarchy h1
  inner join flat f
          on f.level1 = h1.element
  where      h1.parent is null;

这种模式可以重复到下一个级别:

insert into hierarchy (element, parent)
  select     distinct f.level3, h2.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
  where      h1.parent is null;

insert into hierarchy (element, parent)
  select     distinct f.level4, h3.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join hierarchy h3
          on h3.parent = h2.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
         and f.level3 = h3.element
  where      h1.parent is null;

insert into hierarchy (element, parent)
  select     distinct f.level5, h3.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join hierarchy h3
          on h3.parent = h2.id
  inner join hierarchy h4
          on h4.parent = h3.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
         and f.level3 = h3.element
         and f.level4 = h4.element
  where      h1.parent is null;

insert into hierarchy (element, parent)
  select     distinct f.level6, h3.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join hierarchy h3
          on h3.parent = h2.id
  inner join hierarchy h4
          on h4.parent = h3.id
  inner join hierarchy h5
          on h5.parent = h4.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
         and f.level3 = h3.element
         and f.level4 = h4.element
         and f.level5 = h5.element
  where      h1.parent is null;

......等等,直到需要的水平。