2012-08-08 83 views
2

,我在下面的表格处理一些分层数据:SQL遍历父子

Level  Parent PrimaryKey LevelDepth RevenuePct 
Total  NULL  2786f8161   0   100 
US   Total 33f254b0f   1   60 
UK   Total 462adbba   1   25 
Asia  Total 5322678b3   1   15 
Mobile  US  75b72bdf1   2   10 
Laptop  US  813784df5   2   10 
PC   US  9550f97c   2   15 
Consulting US  a44ae3ef8   2   25 
Mobile  UK  ace663d07   2   10 
Laptop  UK  b373e61c   2   8 
PC   UK  ca590ef44   2   7 
Mobile  Asia  d136f267e   2   15 

,我希望它显示在下面的表格:

Breakup      Revenue [%] 
Total       100 
    US       60 
      Mobile    10 
      Laptop    10 
      PC     15 
      Consulting   25 
    UK       25 
      Mobile    10 
      Laptop    8 
      PC     7 
    Asia       15 
      Mobile    15 

的实际问题有6- 7层嵌套。

我对这个领域比较陌生,我试图使用CTE,但是因为子项在不同的父母中重复(即,我有美国,英国的移动类别等),所以我在加入条件方面存在问题。

回答

2

这是一种方法。 Path列用于排序 - 您应该可以不用\连接固定宽度level来生成路径。查询以递归调用cte部分的方式工作,直到cte的第一部分(在union all后的第二部分表示为cte)和table1之间没有行满足连接条件。

; with cte as (
    select level, parent, revenuepct, leveldepth, cast (level as varchar(1000)) Path 
    from table1 
    where parent is null 
    union all 
    select a.level, a.parent, a.revenuepct, a.leveldepth, cast (path + '\' + a.level as varchar(1000)) 
    from table1 a 
    inner join cte 
     on a.parent = cte.level 
) 
-- Simple indentation 
select space(leveldepth * 4) + level as Breakup, 
     revenuepct as [revenue %] 
    from cte 
order by path 
-- Max recursive calls, 0 = unlimited 
option (maxrecursion 10) 

Here is Sql Fiddle with example

And here is a link to article on recursive cte

+0

..感谢您的回复。我想出了一些类似的东西,但如果我们再去一个级别,查询就会失败如果我们在美国和英国有移动电话的子实体ModelA,ModelB和ModelC。 – user1512829 2012-08-08 14:53:15

+0

@ user1512829您需要添加选项(maxrecursion 0),请检查我的更新答案。 – 2012-08-08 14:55:43