0

我真的不需要缩进的结果,这只是我能想到的最好的标题。非常感激任何的帮助。我花了几个小时试图通过 CTE 做到这一点,这似乎是要走的路,但我被困住了。

编辑:我可以按 Component_Job 列对下面的示例数据进行排序,但是,在现实世界中,作业编号是随机的,不一定按任何可用顺序。

我的表包含以下内容:

Root_Job    Parent_Job  Component_Job  
1           1           1a  
1           1           1b  
1           1           1c  
1           1a          1a1  
1           1a          1a2  
1           1b          1b1  
1           1b          1b2  
2           2           2a  
2           2           2b  

我正在尝试创建一个返回以下内容的视图:

Root_Job    Parent_Job  Component_Job
1           1           1a
1           1a          1a1
1           1a          1a2
1           1           1b
1           1b          1b1
1           1b          1b2
1           1           1c
2           2           2a
2           2           2b

只是为了澄清我想要实现的退货单是:

1
  1a
    1a1
    1a2
  1b
    1b1
    1b2
  1c
2
  2a
  2b

最后,我一直在尝试但对我无能为力的 CTE 是:

with BOM (Root_job, parent_job, component_Job)
as
(
-- Anchor member definition
    SELECT e.Root_Job, e.Parent_Job, e.Component_Job
    FROM Bill_Of_Jobs AS e
    WHERE Root_Job = Parent_Job
    UNION ALL
-- Recursive member definition
    SELECT e.Root_Job, e.Parent_Job, e.Component_Job
    FROM Bill_Of_Jobs AS e
    INNER JOIN bill_of_Jobs AS d
    ON e.parent_Job = d.Component_Job
)
-- Statement that executes the CTE
SELECT * from BOM
4

2 回答 2

1

这里可能有一些有用的东西:

declare @Jobs as Table ( ParentJob VarChar(10), ComponentJob VarChar(10) );
insert into @Jobs ( ParentJob, ComponentJob ) values
  ( '1', '1a' ), ( '1', '1b' ), ( '1', '1c' ),
  ( '1a', '1a1' ), ( '1a', '1a2' ), ( '1b', '1b1' ), ( '1b', '1b2' ),
  ( '2', '2a' ), ( '2', '2b' );

select * from @Jobs;

with Roots as (
  -- Find and fudge the root jobs.
  --   Usually they are represented as children without parents, but here they are implied by the presence of children.
  select distinct 1 as Depth, ParentJob as RootJob, Cast( ParentJob as VarChar(1024) ) as Path, ParentJob, ParentJob as ComponentJob
    from @Jobs as J
    where not exists ( select 42 from @Jobs where ComponentJob = J.ParentJob ) ),
  BoM as (
  -- Anchor the indented BoM at the roots.
  select Depth, RootJob, Path, ParentJob, ComponentJob
    from Roots
  union all
  -- Add the components one level at a time.
  select BoM.Depth + 1, BoM.RootJob, Cast( BoM.Path + '»' + J.ComponentJob as VarChar(1024) ), J.ParentJob, J.ComponentJob
    from BoM inner join
      @Jobs as J on J.ParentJob = BoM.ComponentJob )
  -- Show the result with indentation.
  select *, Space( Depth * 2 ) + ComponentJob as IndentedJob
    from BoM
    order by ComponentJob
    option ( MaxRecursion 0 );

现实世界中,很难有这么容易分类的东西。数字项 (1, 1.1, 1.1.1, 1.2) 的技巧是创建一个Path将每个值零填充到固定长度的 a,例如0001, 0001»0001, 0001»0001»0001, 0001»0002,以便它们在按字母顺序排序时正确排序。您的数据可能会有所不同。

于 2013-09-06T18:40:52.300 回答
1
SELECT *
FROM BOM
ORDER BY LEFT(Component_Job+'000',3)
于 2013-09-06T17:39:33.870 回答