DEV Community

Judy
Judy

Posted on

2 1 1 1 1

SQL: Recursive calculation of tree like hierarchical structure #eg83

SQL SERVER has a task table where the id field is the primary key and the parent field is the foreign key pointing to the id, used to describe how multiple nodes form a tree. The root node of a tree is null, and the records with a null parent are the child nodes of the root, that is, the secondary nodes. The weight field only has a value when it is a leaf node.

Image description

Now we need to recursively calculate the hierarchical structure of the tree. Parallel nodes are arranged in order of their IDs, and the new name field=level * underline + original name, which is used to visually represent the hierarchical relationship; The new weight field is the sum of the weights of all subordinate nodes, and the level field represents the hierarchy.

Image description
SPL code:

Image description
A1: Query the database through JDBC.

A2: Create an empty result set.

A3: Filter out the child nodes of the root and loop through these nodes using recursive function.

A4-B6: Function tree, which adds new records to the result set, recursively processes directly subordinate nodes, and returns the weight of the new record. It has four parameters: id, name, weight, and level.

B4: Add new records to the result set and spell out the new name and level. The new weight will be calculated later, so let's set it to 0 for now.

B5: Filter out the direct subordinate nodes of this node, recursively calculate the weights of these nodes, and sum them up.

B6: Calculate the new weight and modify this record to return the new weight.

A7: Return the result set.

Free download

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay