Sql 如何使用ORACLE按树计算组数?

Sql 如何使用ORACLE按树计算组数?,sql,oracle,hierarchical-data,connect-by,Sql,Oracle,Hierarchical Data,Connect By,现在我有一个这样的数据集;8项记录 这棵树的形状如下: root -- 0 --child 100 --sub child 108 ---sub ...(maybe has more level) --child 200 --sub child 205 --child 400 --sub child 423 select cid as node,count(1) as counts from (one subselect for get the 8 records) a

现在我有一个这样的数据集;8项记录

这棵树的形状如下:

root -- 0
--child 100
  --sub child 108
     ---sub ...(maybe has more level)
--child 200
  --sub child 205
--child 400
  --sub child 423
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;
我想计算所有的总和记录,每个子节点不是子节点,子节点的记录应该计算到它的父亲或祖父,直到第一级子节点

因此,结果应该是:

node    counts
100       5
200       1
400       2
但是当我使用start with connect by和with group by关键字时,我无法得到预期的结果

我的sql如下所示:

root -- 0
--child 100
  --sub child 108
     ---sub ...(maybe has more level)
--child 200
  --sub child 205
--child 400
  --sub child 423
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关键字的详细信息

试试这个:

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

您目前的查询结果如何?在group by子句中:group by aid,什么是aid?对不起,它应该是cid,结果为空。当数据集中没有400 0的条目时,-child 400怎么可能是根0的子项。数据集不是树表。它只是记录s的正常数据表。如果它不是树表,为什么需要连接方式?我得到的结果是:400-2,0-6不是除此之外的结果