Skip to content
Advertisement

SQL server: Question about query group and auto id

i have a table which has 2 columns like this, picture is input and output:

enter image description here

Explain input: 2 column is 2 person who relation ship together. Exam: A relation with B, C,D,H Output: i want to merge 2 column , with Column group ID auto and column RelationShip

  • ID group auto: i tried query: row_number() OVER (ORDER BY [columnA]) n
  • RelationShip: is group all person relatioship together and group them to 1 ID group. Exam person A,B,C,D,H realation ship together and group id auto is 1

I have a demo in https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=f81ff386b07589654ad133a8e4b30472

In my query, first i turn the data into a single column, second i count letter, next step i don’t know query.

I tried recursive CTE but error (perhaps I don’t understand clearly about recursive)

I want to solve this problem in sql query.

Advertisement

Answer

You can use a recursive CTE to assign each “column” value a number. This starts by created edges in both directions and then following them:

You can then join this in to assign a group id:

Here is a db<>fiddle.

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