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 および 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;

結果は空です..誰が私を助けることができますか? または、ツリー構造と一緒に使用すると、キーワードによるオラクルのグループの詳細が機能することを誰が知っていますか?

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 に答える