首页 > 解决方案 > 添加到父子关系中的行而不是列

问题描述

这是补充的物料清单结构数据。有父(ParentPart)然后组件和每个组件也可以使用其他组件。

现在使用 LEFT JOIN 我可以添加列,但我想知道如何才能将其作为只有 2 列并拥有 ParentPart,然后是所有组件。

所以它看起来像:

父部件 零件
WN3403 NF0533K
WN3403 571012
... ...

谢谢

已添加图片

标签: sqlsql-server

解决方案


最简单的解决方案是使用 6 个数字和条件列创建,如下所示:

with cte (num) as
(select 1 union all
select num+1 from cte where num <= 6),
your_query as (<put_your_query_here>)
select t.parent_part,
       case when c.num = 1 then level_1_component,
            when c.num = 2 then level_2_component,
            when c.num = 3 then level_3_component,
            when c.num = 4 then level_4_component,
            when c.num = 5 then level_5_component,
            when c.num = 6 then level_6_component
        end as component
   from cte c cross join your_query t

推荐阅读