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

后端 未结 9 2528
耶瑟儿~
耶瑟儿~ 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:58

    SQL in general, like others said, does not handle well such relations. Typically, a surrogate 'relations' table is needed (id, parent_id, unique key on (id, parent_id)), where:

    • every time you add a record in 'table', you:

      INSERT INTO relations (id, parent_id) VALUES ([current_id], [current_id]);

      INSERT INTO relations (id, parent_id) VALUES ([current_id], [current_parent_id]);

      INSERT INTO relations (id, parent_id) SELECT [current_id], parent_id FROM relations WHERE id = [current_parent_id];

    • have logic to avoid cycles

    • make sure that updates, deletions on 'relations' are handled with stored procedures

    Given that table, you want:

    SELECT rel.parent_id, SUM(tbl.points)
    FROM table tbl INNER JOIN relations rel ON tbl.id=rel.id
    WHERE rel.parent_id <> 0
    GROUP BY rel.parent_id;
    

提交回复
热议问题