多次清理

时间:2012-07-12 11:45:00

标签: sql sql-server-2008

我有一对多的桌子已经变得有点乱,我正在寻找更新架构以防止将来发生这种情况。首先,我需要清理现有数据以用作合并脚本的源。不知道如何判断这种类型的查询对谷歌的影响并没有真正帮助。

简单地说,这就是我所看到的以及我想要提取的东西。

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)
  • 组的最低ID应被视为关键
  • 群组成员数量始终少于20
  • 只要结果数据集正确,订购就不重要

非常感谢。

1 个答案:

答案 0 :(得分:4)

这是实现您想要做的事情的一种方式:

这是SQLFiddle

--Let's copy the rows in as they are to begin with
INSERT INTO 
  @Expected
SELECT
   [IdA]
  ,[IdB]
FROM 
  @TestTable


--Lets switch the column values where the higher ID's are in column B  
UPDATE @Expected
SET [KeyId] = [MemberId], [MemberId] = [KeyId]  
WHERE [KeyId] > [MemberId]

--Now lets set the KEY IDs
UPDATE
  E
SET
  E.[KeyId] = E1.[KeyId]
FROM
  @Expected E
INNER JOIN
  @Expected E1 
ON
  E1.[MemberId] = E.[KeyId]

--and you wanted mappings for the keys to themselves in your result set, so let's add those
INSERT INTO
  @Expected
SELECT
  [KeyId]
 ,[KeyId]
FROM
  @Expected E 
WHERE NOT EXISTS
  (SELECT * FROM @Expected WHERE [KeyId] = E.[KeyId] AND [MemberId] = [KeyID])

SELECT DISTINCT 
  * 
FROM 
  @Expected

请注意,我最后选择了DISTINCT,因为我没有从结果集中删除重复项。