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

后端 未结 9 2455
耶瑟儿~
耶瑟儿~ 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;
    
    0 讨论(0)
  • 2021-01-05 10:05

    I would say: create a stored procedure, probably has the best performance. Or if you have a maximum number of levels, you could create subqueries, but they will have a very poort performance.

    (Or you could get MS SQL Server 2008 and get the new hierarchy functions... ;) )

    0 讨论(0)
  • 2021-01-05 10:07

    You have a couple of options:

    1. Use a cursor and a recursive user-defined function call (it's quite slow)
    2. Create a cache table, update it on INSERT using a trigger (it's the fastest solution but could be problematic if you have lots of updates to the main table)
    3. Do a client-side recursive calculation (preferable if you don't have too many records)
    0 讨论(0)
提交回复
热议问题