如何统计树型结构的儿子数啊?(50分)

  • 主题发起人 主题发起人 吴剑明
  • 开始时间 开始时间

吴剑明

Unregistered / Unconfirmed
GUEST, unregistred user!
建立了一个树型结构的数据库:
Parent Self Value
-------- -------- ----------
/ 苹果 $1.3
苹果 小苹果 $1.0
苹果 红苹果 $1.2
/ 梨子 $2.0
梨子 小梨子 $2.1
..........
我希望用条SQL语句(多复杂都没关系),来统计出儿子的个数。
例如:
Seft Count
------- --------
苹果 2
梨子 1
小苹果 0
红苹果 0
小梨子 0

大家想想如何用SELECT把它搞出来,先不要想着用递归。可以再加分
 
select parent as selfname, count(*) as soncount
from mytable group by parent
union
select self as selfname, 0 as soncount
from mytable tb1 where not exists
(select * from mytable tb2
where tb2.parent = tb1.self)

基本思想是先找出所有有儿子的记录再合并上
没有儿子的记录。

这种方法存在两个问题:
1、根节点也被统计了(在前一个选择中加以判断可以去除)
2、只能统计儿子的个数,无法统计出所有子孙后代的个数(怀疑是否
能够只用一条SQL语句完成)。
 
这么复杂的东东还是用存储过程吧
create procedure childcount
declare @self varchar(10)
declare @childcount int
as
begin
create table #temp
(
self varchar(10),
childcount int
)
declare tree_cursor cursor for
select distinct self from fathertable

open tree_cursor
fetch next from tree_cursor into @self
while @@fetch_status=0
begin
select @childcount=count(*) from fathertable where parent=@self
insert into #temp values(@self,@childcount)
fetch next from tree_cursor into @self
end
close tree_cursor
deallocate tree_cursor
select * from #temp
end

OK了吗? 我用的是SQL server 7.0
 
对不起,有一点语法错误,现更正
create procedure childcount
as
declare @self varchar(10)
declare @childcount int
begin
create table #temp
(
self varchar(15),
childcount int
)
set nocount on
declare tree_cursor cursor for
select distinct fiberreelid from fiberreels

open tree_cursor
fetch next from tree_cursor into @self
while @@fetch_status=0
begin
select @childcount=count(*) from fiberreels where parent=@self
insert into #temp values(@self,@childcount)
fetch next from tree_cursor into @self
end
close tree_cursor
deallocate tree_cursor
select * from #temp
end
已经过测试,
》1、根节点也被统计了(在前一个选择中加以判断可以去除)
》2、只能统计儿子的个数,无法统计出所有子孙后代的个数(怀疑是否
能够只用一条SQL语句完成)。
都解决了。
 
搞定:
(SELECT parent AS Seft, COUNT(*) AS countf FROM MyTABLE WHERE parent <> '/'
GROUP BY parent)
UNION
(SELECT self AS seft, 0 AS countf FROM Mytable WHERE self NOT IN
(SELECT parent FROM mytable))

很简单嘛!
 
思路大致如下:
select(所有的爸爸,用group by)
union
(所有的儿子 - 做过爸爸的)
实现见楼上几位大虾

不过只能找到儿子,不能找到孙子
如果要找孙子估计一条sql搞不定了
 
(SELECT parent AS Seft, COUNT(*) AS countf FROM MyTABLE WHERE parent <> '/'
GROUP BY parent)
UNION
(SELECT self AS seft, 0 AS countf FROM Mytable WHERE self NOT IN
(SELECT parent FROM mytable))
 
多人接受答案了。
 
后退
顶部