title: Many to many cleanup
body: <p>I have a many to many table that has become a bit of a mess and I'm looking to update the schema to prevent this happening in future. To do that first I need to clean up the existing data to use as the source of a merge script. Not knowing quite how to term this kind of query hitting Google hasn't really helped.</p>
  
  <p>Broken down simply this is what I'm looking at and what I'm aiming to extract.</p>
  
  <pre><code>DECLARE @TestTable
  TABLE ([IdA] INT, [IdB] INT);
  
  DECLARE @Expected
  TABLE ([KeyId] INT, [MemberId] INT);
  
  INSERT INTO @TestTable
  VALUES
      (1, 2),
      (2, 1),
      (1, 3),
      (4, 1),
      (12, 4),
  
      (5, 6),
      (6, 7),
  
      (8, 9),
  
      (11, 10)
  
  INSERT INTO @Expected
  VALUES
      (1, 1),
      (1, 2),
      (1, 3),
      (1, 4),
      (1, 12),
  
      (5, 5),
      (5, 6),
      (5, 7),
  
      (8, 8),
      (8, 9),
  
      (10, 10),
      (10, 11)
  </code></pre>
  
  <ul>
  <li>Lowest Id of a group should be considered the key</li>
  <li>Number of members of a group will always be less than 20</li>
  <li>Ordering isn't important so long as the resultant dataset is correct</li>
  </ul>
  
  <p>Many thanks.</p>