且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将父/子表转换为固定列的维表

更新时间:2023-02-05 12:58:06

解决方案过于复杂?如果固定在四个深度,则可以通过一些简单的连接来完成...

Overcomplicating the solution? If it's fixed at four deep then it can be done with some simple joins...

SELECT
    L1.id as ID
    L1.Name as Level1
    L2.Name as Level2
    L3.Name as Level3
    L4.Name as Level4
FROM
    RelTable as L1

        INNER JOIN
    RelTable as L2
        ON L1.id = L2.ParentID

        INNER JOIN
    RelTable as L3
        ON L2.id = L3.ParentID

        INNER JOIN
    RelTable as L4
        ON L3.id = L4.ParentID

使用CTE的练习虽然没有用,但可以满足您的需要.

As an exercise in using CTEs its useless, but it does what you need.