以“缩进”顺序返回BOM结果

时间:2013-09-06 17:34:54

标签: sql sql-server

我真的不需要将结果缩进,这只是我能想出的最佳标题。非常感激任何的帮助。我花了好几个小时尝试通过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

2 个答案:

答案 0 :(得分:1)

SELECT *
FROM BOM
ORDER BY LEFT(Component_Job+'000',3)

答案 1 :(得分: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,其每个值都填充为零填充到固定长度,例如: 00010001»00010001»0001»00010001»0002,以便在按字母顺序排列时排序正确。您的数据可能会有所不同。