How to calculate the sum of values in a tree using SQL

后端 未结 9 2501
耶瑟儿~
耶瑟儿~ 2021-01-05 09:29

I need to sum points on each level earned by a tree of users. Level 1 is the sum of users\' points of the users 1 level below the user. Level 2 is the Level 1 points of the

9条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 09:48

    You can write a simple recursive function to do the job. My MSSQL is a little bit rusty, but it would look like this:

    CREATE FUNCTION CALC
    (
    @node integer,
    )
    returns 
    (
    @total integer
    )
    as
    begin
        select @total = (select node_value from yourtable where node_id = @node);
    
        declare @children table (value integer);
        insert into @children   
        select calc(node_id) from yourtable where parent_id = @node;
    
        @current = @current + select sum(value) from @children;
        return
    end
    

提交回复
热议问题