创建父/子关系的平面结构

时间:2018-12-05 06:35:14

标签: sql tsql

Input

我有一个多达10个级别的父母/孩子关系表,如上面所定义,并且需要按照以下屏幕截图输出,该屏幕截图将采用扁平结构。

Output

下面是创建表和插入示例数据的代码。

https://parseapi.back4app.com/

1 个答案:

答案 0 :(得分:2)

SELECT
  L0.CCNAME,
  L1.CCNAME,
  L2.CCNAME,
  L3.CCNAME,
  L4.CCNAME,
  L5.CCNAME,
  L6.CCNAME,
  L7.CCNAME,
  L8.CCNAME,
  L9.CCNAME
FROM
            dbo.CCTemp AS L0
  LEFT JOIN dbo.CCTemp AS L1 ON L1.parentID = L0.id
  LEFT JOIN dbo.CCTemp AS L2 ON L2.parentID = L1.id
  LEFT JOIN dbo.CCTemp AS L3 ON L3.parentID = L2.id
  LEFT JOIN dbo.CCTemp AS L4 ON L4.parentID = L3.id
  LEFT JOIN dbo.CCTemp AS L5 ON L5.parentID = L4.id
  LEFT JOIN dbo.CCTemp AS L6 ON L6.parentID = L5.id
  LEFT JOIN dbo.CCTemp AS L7 ON L7.parentID = L6.id
  LEFT JOIN dbo.CCTemp AS L8 ON L8.parentID = L7.id
  LEFT JOIN dbo.CCTemp AS L9 ON L9.parentID = L8.id