我先描述下我遇到的难题:
我现在手里有一个表,里面记录着一些单位统计到的数据,但是统计到的数据都是该单位本身的。
而我需要的数据是汇总的数据,意思是说我需要得到单位本身的数据和该单位所有下级单位(如果该单位有下级的话)的数据之和关于表结构、单位层级关系、我需要统计的数据我都用下图画出来了
表一:单位表
id         varchar(50)
name       varchar(50)
parent     varchar(50)
ancestor   varchar(50)表二:单位本身的统计数据
t1_id   varchar(50)
count   int图片中“我希望统计后的数据”是单位本身的数据加上该单位所有下级单位的数据之和。
例如id为10001的单位它有10002、10003、10004,所以10001的汇总后的count为39
例如10003的单位它有一个下级10004,所以10003的汇总后的count为30哪位高手能帮我解决这个问题啊,卡了好几天了!图:

解决方案 »

  1.   


    create table t1(id int,[name] varchar(100),parent int)
    insert into t1
    select 10000,'xx1',0 union all
    select 10001,'xx2',10000 union all
    select 10002,'xx3',10001 union all
    select 10003,'xx4',10001 union all
    select 10004,'xx5',10003 union all
    select 10005,'xx6',10000
    gocreate table t2(id int,cnt int)
    insert into t2
    select 10001,5 union all
    select 10002,4 union all
    select 10003,10 union all
    select 10004,20 union all
    select 10005,12
    go;with cte as
    (
    select id,cnt,id as po from t2
    union all
    select t.id,b.cnt,a.id
    from t1 a join cte t on a.parent = t.po
      join t2 b on a.id = b.id
    )select id,sum(cnt) cnt
    from cte
    group by iddrop table t1,t2/****************id          cnt
    ----------- -----------
    10001       39
    10002       4
    10003       30
    10004       20
    10005       12(5 行受影响)
      

  2.   

    厉害厉害,不过能不能不用临时表,直接用sql语句来实现啊
      

  3.   

    这涉及到递归的一些处理,如果按照某条SQL语句来处理,可能需要加一个得到子级的函数,按函数来做。
      

  4.   

    很好的题目,正好我想练练cte递归,拿走了,另外把lz的图贴上.
      

  5.   

    不懂递归吖,能不能输出3L 那个cte子表给我看看,顺便简单讲解一下?
      

  6.   

    SELECT id, 
        (
             SELECT SUM(count)
             FROM T2
             WHERE t1_id IN (SELECT id FROM T1 WHERE id = a.id OR ancestor LIKE '%' + a.id + '%')
        )
    FROM T1 a
      

  7.   

    公用表表达式 (CTE)和临时表不是一个概念