【问题标题】:Transform a parent/child table to a fixed column dimentional table将父/子表转换为固定列维度表
【发布时间】:2010-10-26 15:45:52
【问题描述】:

我有一个关系表(id、parentId、name)

我想将其转换为平面尺寸表

(id, Level1, Level2, Level3, Level4)

我可以将深度固定为 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

我做错了什么?

【问题讨论】:

  • 如果您向我们展示您开始使用的数据可能会有所帮助。

标签: sql-server pivot olap recursive-query


【解决方案1】:

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

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 的练习,它没有用,但它可以满足您的需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多