• ramos.ferdinand (10/17/2013)


    DDL:

    IF object_id('tempdb..#testEnvironment') IS NOT NULL

    BEGIN;

    DROP TABLE #testEnvironment;

    END;

    SELECT [Car], [Child], [Parent], [Category_Name]

    INTO #testEnvironment

    FROM (VALUES('Type R',16369,14499,NULL),

    (NULL,14499,14498,'Civic'),

    (NULL,14498,14371,'Manual Transmission'),

    (NULL,14371,234,'2013'),

    (NULL,234,225,'Gasoline'),

    (NULL,225,1,'Passenger Car'),

    (NULL,1,0,'Honda'),

    ('SX 2.0',17273,6267,NULL),

    (NULL,6267,6265,'CRV'),

    (NULL,6265,6264,'Automatic Transmission'),

    (NULL,6264,234,'2013'),

    (NULL,234,6199,'Diesel'),

    (NULL,6199,1,'SUV'),

    (NULL,1,0,'Honda')

    )a([Car], [Child], [Parent], [Category_Name]);

    Using the above sample data, you can unravel the hierarchy using a recursive CTE and then do a cross tab query to PIVOT.

    WITH UnravelHiearchy AS

    (

    SELECT Level=0, Car, Child, Parent, Category_Name

    FROM #TestEnvironment

    WHERE Car IS NOT NULL

    UNION ALL

    SELECT Level+1, a.Car, b.Child, b.Parent, b.Category_Name

    FROM UnravelHiearchy a

    JOIN #TestEnvironment b ON a.Parent = b.Child

    )

    SELECT Car

    ,Level1=MAX(CASE WHEN Level = 1 THEN Category_Name END)

    ,Level2=MAX(CASE WHEN Level = 2 THEN Category_Name END)

    ,Level3=MAX(CASE WHEN Level = 3 THEN Category_Name END)

    ,Level4=MAX(CASE WHEN Level = 4 THEN Category_Name END)

    ,Level5=MAX(CASE WHEN Level = 5 THEN Category_Name END)

    ,Level6=MAX(CASE WHEN Level = 6 THEN Category_Name END)

    FROM UnravelHiearchy

    GROUP BY Car

    ORDER BY Car;

    This way, you'd need to know the maximum number of levels for any car, and add Leveln= up to that level.

    The alternative if you don't know the number of levels is that you could insert the unraveled hierarchy into a temp table and then use that along with some dynamic SQL to PIVOT the number of Level columns you need.

    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs [/url]

    Edit: Sorry to be a bit redundant with what Cadavre posted. No coffee yet this morning so I didn't read it carefully.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St