将相同的密钥添加到匹配的对

时间:2013-09-19 11:10:38

标签: sql sql-server db2

情况如下。在将文件与自身匹配以进行重复数据删除之后,我们将留下以下成对的匹配记录:

Key1 - Key2
Key1 - Key3
Key2 - Key1
Key2 - Key3
Key3 - Key1
Key3 - Key2

我想以某种方式为此添加一个唯一的群集密钥,以便我们在相同的密钥下留下所有这些记录。所以在这种情况下,我们将有一个单独的密钥,将Key1,Key2和Key 3标识为同一个。

欢迎任何帮助。

谢谢,

多鲁

1 个答案:

答案 0 :(得分:0)

您似乎拥有彼此完全相同的完整密钥列表。假设您有一张包含这两个键的表。以下查询返回任何给定键的最小键值:

select key1,
       (case when key1 < min(key2) over (partition by key1) then key1
             else min(key2) over (partition by key1) 
        end) as newkey
from keypairs kp
group by key1;

这为每个键提供了一个查找值。要将它应用于您的表(在SQL Server或DB2中):

select t.*, coalesce(keymap.newkey, t.key) as newkey
from YourTable t left outer join
     (select key1,
             (case when key1 < min(key2) over (partition by key1) then key1
                   else min(key2) over (partition by key1) 
              end) as newkey
      from keypairs kp
      group by key1
     ) keymap
     on t.key = keymap.key1;

更新查询类似。

相关问题