Write SQL query to put hirarchy-based data into Level-based table format

G C 21 Reputation points
2022-01-10T19:18:04.793+00:00

Hi all, Can someone please help me putting the sql query from one table into the format shown in the attached picture?
I have a merhcant hierarchy data stored into one table and I would like to transform that into Level-based table format.

Thank you.163628-capture.png

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Tom Phillips 17,781 Reputation points
    2022-01-10T21:05:58.56+00:00

    Since you only have 4 levels this would be simplest.

    ;with levelcte AS (
        SELECT DISTINCT 
            [FOB #] as [Level1],
            NULL as [Level2],
            NULL as [Level3],
            NULL as [Level4],
            [FOB] as [Description]
        FROM tablename
        UNION ALL
        SELECT DISTINCT
            [FOB #] as [Level1],
            [DIV #] as [Level2],
            NULL as [Level3],
            NULL as [Level4],
            [DIVISION] as [Description]
        FROM tablename
        UNION ALL
        SELECT DISTINCT
            [FOB #] as [Level1],
            [DIV #] as [Level2],
            [DEPT#] as [Level3],
            NULL as [Level4],
            [DEPARTMENT] as [Description]
        FROM tablename
        UNION ALL
        SELECT DISTINCT
            [FOB #] as [Level1],
            [DIV #] as [Level2],
            [DEPT#] as [Level3],
            [CLS #] as [Level4],
            [CLASS] as [Description]
        FROM tablename
    )
    SELECT *
    levelcte
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.