如何用树计算组使用ORACLE?

时间:2015-09-29 06:44:18

标签: sql oracle hierarchical-data connect-by

现在我有一个像这样的数据集; (8条记录)

cid    pid 
108    100 
108    100 
423    400 
423    400 
100    0   
100    0   
100    0   
200    0   

树如下:

root -- 0
--child 100
  --sub child 108
     ---sub ...(maybe has more level)
--child 200
  --sub child 205
--child 400
  --sub child 423

我希望每个孩子都计算所有总和记录(不是子孩子,子孩子的记录应计算到它的父亲或祖父,直到第一级子节点)。

所以结果应该是:

node    counts
100       5
200       1
400       2

但是当我使用start with connect和group by keywords时,我无法获得预期的结果。

我的sql如下:

select cid as node,count(1) as counts 
from (one subselect for get the 8 records) a 
start with a.pid = '0' 
connect by prior a.cid = a.pid) t group by cid;

结果为空.. 谁能帮我?或者谁知道关键字的oracle组的详细信息与树结构一起使用时有效?

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT top_cid, Count(1) FROM (
  WITH
    parent_child as (
      select distinct a.cid, a.pid from a
      union  
      select a.pid, 0 from a
      where a.pid<>0 and not exists (
        select 1 from a a1 where a1.cid=a.pid
      )
    ),
    tree as (
      select level as lvl,
        --connect_by_root in 10g and above
        replace(sys_connect_by_path(decode(level, 1, cid), '~'), '~') AS top_cid, 
        pid, cid 
      from parent_child
      start with pid = 0
      connect by prior cid = pid(+)
    )
  select tree.top_cid, a.pid, a.cid 
  from a, tree
  WHERE a.cid=tree.cid
) GROUP BY top_cid