SQL 服务器:根据父子关系拆分列

SQL Server : split column based on parent child relationship

table两列之间的父子关系如下:

我想将 ID 列拆分为 3 个不同的列,如下所示:

基本上 0ParentID 的那一个会在 Cat1 中。 Cat2 通过 ParentID 链接到 Cat1,类似地,Cat3 链接到 Cat2

如果有人有解决此问题的方法,请分享您的想法?

这是一个简单的查询。你实际上已经完美地描述了查询应该做什么。

让我们一步步来:

Basically the one which has 0 as ParentID would be in Cat1.

所以第一步是获取Cat1值:

SELECT Cat1.id FROM tablename AS Cat1
WHERE Cat1.ParentID = 0

Cat2 is linked with Cat1 by ParentID

这是一个 JOINLEFT JOIN 具体来说,因为显然你想在这些列中获取具有 null 值的行,如果没有这样的行 ParentID:

SELECT Cat1.id, Cat2.id FROM tablename AS Cat1
LEFT JOIN tablename AS Cat2 ON Cat2.ParentID = Cat1.id
WHERE Cat1.ParentID = 0

similarly Cat3 is linked to Cat2.

现在,我们对 Cat3 做同样的事情:

SELECT Cat1.id, Cat2.id, Cat3.id FROM tablename AS Cat1
LEFT JOIN tablename AS Cat2 ON Cat2.ParentID = Cat1.id
LEFT JOIN tablename AS Cat3 ON Cat3.ParentID = Cat2.id
WHERE Cat1.ParentID = 0