0

现在我有一个这样的数据集;(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 by 和 with group by 关键字时,我无法获得预期的结果。

我的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 group by 关键字的详细信息在与树结构一起使用时起作用?

4

1 回答 1

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
于 2015-09-29T08:47:44.550 回答