0

私はリレーショナルテーブル(id、parentId、name)を持っています

フラット化された次元テーブルに変換したい

(id、レベル1、レベル2、レベル3、レベル4)

深さを 4 に固定しても問題ありません。

再帰的な CTE とピボットを使用して進歩しましたが、結果セットが正しくありません

私は得る

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

しかし、私は必要です

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

ここに私がデートしなければならないものがあります

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

私は何を間違っていますか?

4

1 に答える 1

2

ソリューションが複雑になりすぎていませんか? 深さ 4 で固定されている場合は、いくつかの単純な結合で実行できます...

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 を使用する演習としては役に立ちませんが、必要なことは実行します。

于 2010-10-26T17:34:56.693 に答える