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

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

    If you are working with trees stored in a relational database, I'd suggest looking at "nested set" or "modified preorder tree traversal". The SQL will be as simple as that:

    SELECT id, 
           SUM(value) AS value 
    FROM table 
    WHERE left>left\_value\_of\_your\_node 
      AND right<$right\_value\_of\_your\_node;
    

    ... and do this for every node you are interested in.

    Maybe this will help you: http://www.dbazine.com/oracle/or-articles/tropashko4 or use google.

提交回复
热议问题