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

后端 未结 9 2517
耶瑟儿~
耶瑟儿~ 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 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)

提交回复
热议问题