【问题标题】:Can self referencing table pivot to show family lineage for every child with generation count giving rise to the names of each column?自引用表是否可以通过生成每个列的名称来显示每个孩子的家庭血统?
【发布时间】:2020-02-13 17:35:04
【问题描述】:

我有一个父母和孩子的自引用表,并且我已经编写了一个递归 CTE,所以我现在有一个父子关系列表,其中包含它们对它们的深度,即它们在哪一代。 现在是否可以将其旋转以在左列中显示曾祖父母的 ID,然后在下一列中显示祖父母,然后是父母,然后是孩子等,请以他们各自的世代作为列标题?

例如您看到我正在插入临时表的数据,我可以得到这个吗?

Gen0    Gen1        Gen2        Gen3        Gen4
1       2           3           4           5
10      20          100         1000
10      20          200     
10      30
10      40
create table [#Data] ([ParentId] int, [ChildId] int)
insert [#Data] values
    (1, 2)
    , (2, 3)
    , (3, 4)
    , (4, 5 )
    , (10, 20)
    , (10, 30)
    , (10, 40)
    , (20, 100)
    , (20, 200)
    , (200, 1000)

;with [CTE] AS
    (
    select [A].[ParentId], [A].[ChildId], 1 as [Generation]
    from [#Data] [A]
    left join [#Data] [B]
        on [A].[ParentId] = [B].[ChildId]
    where [B].[ChildId] is null
    union all
    select [D].[ParentId], [D].[ChildId], [Generation] + 1
    from [CTE] [C]
    join [#Data] [D]
        on [C].[ChildId] = [D].[ParentId]
    )
    select * from [CTE] order by [ParentId], [ChildId]

我正在使用 SQL 2017。 非常感谢您的关注。

【问题讨论】:

    标签: sql-server recursion pivot parent-child common-table-expression


    【解决方案1】:

    您可以使用类似的方法来查询您的 CTE:

    ;with [CTE] AS
    (/*your code here*/)
    select 
          g1.[ParentId]                         as Gen0
       ,  coalesce(g1.[ChildId], g2.[ParentId]) as Gen1
       ,  coalesce(g2.[ChildId], g3.[ParentId]) as Gen2
       ,  coalesce(g3.[ChildId], g4.[ParentId]) as Gen3
       ,  g4.[ChildId]                          as Gen4
    from 
        [CTE] as g1
        left join [CTE] as g2 on g1.[ChildId] = g2.[ParentId]
        left join [CTE] as g3 on g2.[ChildId] = g3.[ParentId]
        left join [CTE] as g4 on g3.[ChildId] = g4.[ParentId]
    
    where g1.[Generation] = 1
    

    结果:

    查看完整代码here。这是一个静态解决方案,如果您想要使用任意代数的东西,您必须在动态 TSQL 中转换此代码。

    附:我认为您的预期结果可能有一个错字:在 Gen3 列中,第 1000 列应该在第三行,而不是在第二行,因为 1000 是 200 的子项,而不是 100 的子项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 2016-05-09
      • 1970-01-01
      • 2011-12-19
      • 2020-12-20
      • 2011-08-18
      相关资源
      最近更新 更多