Domanda

Ho una tabella relazionale (id, parentId, nome)

che vorrei convertire in un appiattito tavolo tridimensionale

(id, Livello1, Livello2, Level3, Livello4)

Sono ok fissa la profondità a 4 profondo.

Ho fatto progressi con una CTE ricorsiva e perno, ma il set di risultati non è giusto

ho

Id  Name   Level1 Level2
0   Root   NULL   NULL
1   NULL   L1     NULL

Ma ho bisogno

Id  Name   Level1 Level2
0   Root   NULL   NULL
1   Root   L1     NULL

Ecco quello che ho fino ad oggi

with rcte as
(
      select h.id
      ,h.parent_id
      ,h.name
      ,1 as HierarchyLevel 
  FROM RelTable h
  where id = 1
  union all
  select h2.id
       , h2.parent_id 
      , h2.name
      , r.HierarchyLevel + 1 AS HierarchyLevel 
  FROM RelTable h2
  inner join rcte r on h2.parent_id = r.id
 )
select id, parent_id, [1] as L1,[2] as L2,[3] as L3, [4] as L4
from (
select id,parent_id,name,HierarchyLevel from rcte
) as src
pivot  ( max(name)  for HierarchyLevel   in ([1],[2],[3],[4]) ) as pvt

quello che sto facendo di sbagliato?

È stato utile?

Soluzione

overcomplicating la soluzione? Se è fissato a quattro profonda allora può essere fatto con qualche semplice unisce ...

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

Come esercizio nell'utilizzo CTE sua inutile, ma fa quello che ti serve.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top