开发者

Complex aggregate functions and hierarchical structures in SQL

I want to store a tree structure of arbitrary depth in an SQL database (MySQL, but want to avoid DBMS-specific features). Now I want to compute a value N for each node as follows:

  • first, calculate the sum of a certain column in all (immediate) children of the current node which are leaves (i.e. have no children)
  • then, calculate the maximum of the values N of each of the remaining children, i.e. those with children
  • finally, add the results of the first two steps to get the value N for the current node

Obviously, this involves a recursion, so nested sets seem to be the representation of choice for this scenario. However, I couldn't work out how to f开发者_运维百科ormulate the calculation above as an SQL query. It is easy to get the SUM() or MAX() of all the descendants, but the way the aggregate functions are combined complicates the matter greatly. Does anyone have a solution?


What if the schema also had additional computed columns such as depth and "is leaf node"?

It would require more maintenance (not that nested sets are maintenance free) but I think it puts the above query within reach using "standard" SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜