Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Identify related rows (Hierarchal)
    primarykey
    data
    text
    <p>I need to identify rows that are related to each other using two fields, to some extent it is a hierarchy, but cant get CTE to work.</p> <p>This is a simplified table:</p> <pre><code>CREATE TABLE [dbo].[LinkedRows]( [ID] [int] NULL, [COL1] [nvarchar](50) NULL, [COL2] [nvarchar](50) NULL, [LINK] [int] NULL ) ON [PRIMARY] </code></pre> <p>Here's some data:</p> <pre><code>INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (1, 'A','B') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (2, 'C','B') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (3, 'A','D') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (4, 'D','A') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (5, 'B','A') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (6, 'E','C') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (7, 'B','C') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (8, 'C','E') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (9, 'F','G') INSERT INTO dbo.LinkedRows (ID, COL1, COL2) VALUES (10, 'G','H') </code></pre> <p>This is what I'm trying to determine:</p> <pre><code>ID COL1 COL2 linked 1 A B 1 2 C B 1 3 A D 1 4 D A 1 5 B A 1 6 E C 1 7 B C 1 8 C E 1 9 F G 2 10 G H 2 </code></pre> <p>Rows 1 and 2 both have B in COL2, so A, B and C are all related to each other and have been given the same linked number (ID). In rows 3 and 4 we have A,D and D,A since there is a combination of B,A in row 5, D can be linked to B through A, so now we can link A, B, C, D together. In row 6 and 8 we have E,C and C,E so we can now link A, B, C, D, E together. Row 7 is just the opposite of row 2. In row 9 we have F,G since we cant make a link from either of these to A,B,C,D,E another linked group is created. In row 10 we have G,H which can be linked to linked group 2 through G ie, F,G,H are related.</p> <p>Any help or advice greatly appreciated.</p> <p>Regards CM</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload