表cat
catId(int)    catName(nvarchar(40))    parentId(int)
1              a                       0
2              a                       1
3              a                       1
4              a                       2
5              a                       3表cat_money
catId(int)    money(int)1               10
2               20
3               30
4               40
1               12
3               35
5               50我需要统计出来 每个 cat 的 money其中 没有孩子的cat 的 money 就是它在cat_money表内的money的值的和
任何一个有孩子的cat 的 money  是它自己在cat_money表内的money的值的和加上所由孩子、孙子、重孙....在cat_money表内的money的值的和表设计这样了,客是确想不出如何来统计了,请大家帮忙谢谢。

解决方案 »

  1.   

    另外 当cat_money 没有 某个有孩子的 cat 的纪录的 时候  仍然要 统计处它
    也就是  取出 它所由孩子、孙子...的 money 的和晕,怎么想是再算传销的帐啊。;-)
      

  2.   

    另外 同样的表结构
    请问 如何取得 每个cat在 cat_money 内出现的 次数 
    同样是要求   父亲的次数 = 自己的次数 + 子、孙的次数和谢谢!!!
      

  3.   

    create table cat(catId int,catName nvarchar(40),parentId int)
    create table cat_money(catId int,money int)
    insert into cat select '1','a','0'
    union all
    select '2','b','1'
    union all
    select '3','c','1'
    union all
    select '4','d','2'
    union all
    select '5','e','3'insert into cat_money select '1','10'
    union all
    select '2','20'
    union all
    select '3','30'
    union all
    select '4','40'
    union all
    select '5','50'
    goCreate FUNCTION fn_catid()
    RETURNS @t TABLE(ID int,Level int,SID varchar(8000))
    AS
    BEGIN
    DECLARE @Level int
    SET @Level=1
    INSERT @t SELECT catID,@Level,','+CAST(catID as varchar)+','
    FROM cat
    WHERE parentId=0
    WHILE @@ROWCOUNT>0
    BEGIN
    SET @Level=@Level+1
    INSERT @t SELECT a.catID,@Level,b.SID+CAST(a.catID as varchar)+','
    FROM cat a,@t b
    WHERE a.ParentId=b.ID
    AND b.Level=@Level-1
    END
    RETURN
    ENDGOSELECT a.catID,a.parentId,SUM_Money=SUM(b.Money)
    FROM cat a,fn_catid() a1,
    cat_Money b,fn_catid() b1
    WHERE a.catID=a1.ID
    AND b.catID=b1.ID
    AND b1.SID LIKE a1.SID+'%'
    GROUP BY a.catID,a.parentId