如何获取Oracle树层次结构中所有父项的总子数?

时间:2013-11-11 07:06:04

标签: sql tree oracle11g

我有一个Oracle Tree层次结构,它基本上类似于下面的表MY_TABLE

(LINK_ID,
 PARENT_LINK_ID,
 STEP_ID )

在MY_TABLE中包含以下示例数据:

LINK_ID     PARENT_LINK_ID      STEP_ID
-----------------------------------------------
A           NULL                0
B           NULL                0
AA          A                   1
AB          A                   1
AAA         AA                  2
BB          B                   1
BBB         BB                  2
BBBA        BBB                 3
BBBB        BBB                 3

根据上面的示例数据,我需要生成一个报表,该报表基本上返回所有子项的总行数 两个父链接ID(仅需要顶级),也就是说,我需要生成一个返回以下信息的SQL查询,即:

PARENT  RESULT COUNT
----------------------------
A       3
B       4   

所以我需要汇总属于所有(父)链接ID的子项,其中LINK_ID的PARENT_LINK_ID为NULL

2 个答案:

答案 0 :(得分:1)

我认为是这样的:

select link, count(*)-1 as "RESULT COUNT"
  from (
    select connect_by_root(link_id) link
    from my_table
    connect by nocycle parent_link_id = prior link_id
    start with parent_link_id is null)
group by link
order by 1 asc

答案 1 :(得分:0)

请尝试:

WITH parent(LINK_ID1, LINK_ID, asCount) AS
(
  SELECT LINK_ID LINK_ID1, LINK_ID, 1 as asCount  
  from MY_TABLE WHERE PARENT_LINK_ID is null

  UNION ALL 

  SELECT LINK_ID1, t.LINK_ID, asCount+1 as asCount  FROM parent
  INNER JOIN MY_TABLE t ON t.PARENT_LINK_ID =  parent.LINK_ID
    )
select 
  LINK_ID1 "Parent", 
  count(asCount)-1 "Result Count"
From parent 
group by LINK_ID1;

SQL Fiddle Demo