简体   繁体   English

如何在 SQL 数据库中创建层次结构?

[英]How to create a hierarchy structure in SQL database?

I have a table with the following columns:我有一个包含以下列的表格:

在此处输入图像描述

I need to create more columns based on the number of levels and based on the hierarchy.我需要根据级别数和层次结构创建更多列。

For example:例如:

Level 1
Architecture ->Level 2
             ->Asses Inventory ->level 3
                              ->Program

I need create three columns if there are a maximum of three levels.如果最多三个级别,我需要创建三列。 I have achieved this in PowerBI.我在 PowerBI 中实现了这一点。

在此处输入图像描述

How can I achieve the same thing in SQL?如何在 SQL 中实现相同的目标? Any help is appreciated.任何帮助表示赞赏。 Thanks谢谢

In T-SQL I'd just join the table to itself multiple times在 T-SQL 中,我只是多次将表加入到自身中

Create a new table how you want it then something like:创建一个你想要的新表,然后是这样的:

   INSERT INTO NEW_TABLE
(LEVEL1, LEVEL2, LEVEL3)
SELECT
a.name,
b.name,
c.name
FROM TABLE1 a
LEFT OUTER JOIN TABLE1 b
ON a.category_id = b.parent_id
LEFT OUTER JOIN TABLE1 c
on b.category_id = c.parent_id
GO

That should do what you're after I think.那应该按照我的想法去做。

You can use hierarchyid type.您可以使用hierarchyid类型。 It comes with a lot of methods to work with the hierarchy itself like:它带有很多方法来处理层次结构本身,例如:

  • GetAncestor获取祖先
  • GetDescendant获取后代
  • GetLevel获取级别
  • GetRoot获取根
  • IsDescendantOf是后代的

In your example, you will have something like this:在您的示例中,您将拥有如下内容:

ID      Name
/1/     Architecture
/1/1/   Asses Invenctory
/1/2/   Process2
/2/     Assset Management 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM