Skip to content
Advertisement

How can create a new table from another after Calculate Some Field

I have a table called WorkSpace with 4 columns.

Each record in this table refers to their parent record through the Parent_id column.

You should continue this cycle until you reach the main parent and all of these steps specified in the View_Parent_id column.

The ID of main parent number is specified by 1.

So now I want create a NEW_WorkSpace table and separate each of the values in View_Parent_id column into a separate column.

The View_Parent_id column is ultimately 15 value so we need 15 columns in new table (Level_1…Level_15).

I used the loop in my query but it was very slow.

WorkSpace table has 1.5 million rows.

WorkSpace table:

NEW_WorkSpace table:

My code:

Thank you for your help.

Advertisement

Answer

I would approach this using string operations on view_parent_id. Then aggregating the final result:

Here is a db<>fiddle.

As for processing. Probably the most expensive part of the query is the aggregation after the recursive CTE. The recursive portion is not doing any joining, so it should be fairly fast (string operations can be slow).

The join to get the label is using correct types, so an index on w_id can be used.

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