Skip to content
Advertisement

Hierarchical cumulative sum in sql query (id,parentId) structure

I have two tables that I want to get all accounts and their Credit sum and Debit sum even parent records have to sum thier child values

I’m implementing Id ParentId Structure .

1- [AccountChart] Table with these fields :

2- [Transaction] Table with these fields

here is what I tried

the problem that I couldn’t bring the summary values for the parent records.

the results I get is :

but I excpect to be calculate the childs in parent as this

Advertisement

Answer

I like the technique of using Range Keys. If you have a slow moving hierarchy, I would create a table to store these values

Just to expand, the range keys facilitate selection, and variable depth aggregation.

You may notice that the SEQ has an Order by AccountName. In my GL systems, we have a column for presentation sequence. This controls the order rather than ALPHA on name or significant digits on the account.

Example

Returns

enter image description here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement