Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is my solution <a href="http://sqlfiddle.com/#!3/b5b38/1/0" rel="nofollow">SQL Fiddle</a></p> <p>The nature of the relationships require looping as I figure.</p> <p><BR> Here is the SQL:</p> <pre><code>--drop TABLE Table1 CREATE TABLE Table1 ([row] int identity (1,1),GroupID INT NULL,[Company] varchar(2), [Publisher] varchar(2)) ; INSERT INTO Table1 (Company, Publisher) select left(newid(), 2), left(newid(), 2) declare @i int = 1 while @i &lt; 8 begin ;with cte(Company, Publisher) as ( select left(newid(), 2), left(newid(), 2) from Table1 ) insert into Table1(Company, Publisher) select distinct c.Company, c.Publisher from cte as c where not exists (select * from Table1 as t where t.Company = c.Company and t.Publisher = c.Publisher) set @i = @i + 1 end; CREATE NONCLUSTERED INDEX IX_Temp1 on Table1 (Company) CREATE NONCLUSTERED INDEX IX_Temp2 on Table1 (Publisher) declare @counter int=0 declare @row int=0 declare @lastnullcount int=0 declare @currentnullcount int=0 WHILE EXISTS ( SELECT * FROM Table1 where GroupID is null ) BEGIN SET @counter=@counter+1 SET @lastnullcount =0 SELECT TOP 1 @row=[row] FROM Table1 where GroupID is null order by [row] asc SELECT @currentnullcount=count(*) from table1 where groupid is null WHILE @lastnullcount &lt;&gt; @currentnullcount BEGIN SELECT @lastnullcount=count(*) from table1 where groupid is null UPDATE Table1 SET GroupID=@counter WHERE [row]=@row UPDATE t2 SET t2.GroupID=@counter FROM Table1 t1 INNER JOIN Table1 t2 on t1.Company=t2.Company WHERE t1.GroupID=@counter AND t2.GroupID IS NULL UPDATE t2 SET t2.GroupID=@counter FROM Table1 t1 INNER JOIN Table1 t2 on t1.publisher=t2.publisher WHERE t1.GroupID=@counter AND t2.GroupID IS NULL SELECT @currentnullcount=count(*) from table1 where groupid is null END END SELECT * FROM Table1 </code></pre> <p>Edit: Added indexes as I would expect on the real table and be more in line with the other data sets Roman is using.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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