Skip to content
Advertisement

SQL Recursive Count

I have two tables I am joining with the following structure:

A ContentDivider can have n ContentDividers as Children and can have m CustomPages as children as well. I want a View that counts the Display the current CustomDivider and the COunt for all the CustomPages as Children of the current ContentDivider.

My Test data:

And the View I want to extend:

As for now the view counts the custompages directly underneath the contentdivider. I would like all the CustomPages as children counted. Any suggestions?

The respected result would be:

View

Advertisement

Answer

this sounds like a perfect situation for recursive cte 😉 So, if I understood correctly, your expected result would be Toplevel1 with 6 pages and Toplevel 2 with 2 pages since all the other levels are somewhere beneath these two mentioned levels?

The cte might look something like this (maybe you habe to include the max recursion option):

This leads to all pages being assigned to its top level.

See fiddle for details: http://sqlfiddle.com/#!18/f1a44/28/1

Edit: Since you need the details down to DividerID, I extended my example in the fiddle. First of all, I fetch the PageCount per ID in one cte and additionally the PageCount aggregated on level (ParentID and all its IDs) – this done you don’t need the count and grouping in the following ctes. In my query I then check, if my current rows ID is a top-level of any kind and assign the corresponding PageCount to this row.

See new fiddle for details: http://sqlfiddle.com/#!18/f1a44/185/1

I’m mot sure, if there is a prettier / nicer way to solve this, but seemingly this seems to solve the problem. However, I did NOT check if it works if any number of sublevels or whatsoever – if you find any issues, feel free to comment.

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