0

一个简单的问题是,您如何使用 PK 获取一组记录,并为每个源创建两个记录,并为重复项稍微更改密钥?换句话说,我获取 4000 条记录并生成 8000 条记录,其中 4000 条是相同的,而其他 4000 条的密钥稍有改变。我不能做一个工会,因为这本质上是两个选择(长篇大论)。

其余的变得复杂,但可能有必要提供示例。

这是我的原始集(它包含超过 4000 条记录)

dateGroup areaGroup itemID editionID
   1          1        1       1
   1          1        1       2
   1          2        1       1
   1          2        2       1

   2          1        1       1
   2          1        1       2
   2          2        1       1
   2          2        1       2

对于每条记录,我需要创建一个重复的记录,将 areaGroups 在“0”下组合在一起,然后创建一个逗号分隔的原始 areaGroups 列表作为单独的字段。(“为什么”是一些愚蠢的程序员(我)在大约 15 年前犯了一个错误。)我可以根据需要重新编号 editionID,但原始记录和重复记录必须具有相同的 editionID(因此联合不起作用) . PK 和上面一样(所有字段)

dateGroup areaGroup itemID editionID aGroups
   1          0        1       1        1
   1          0        1       2        1
   1          0        1       1        2    // Duplicate (EditionID)
   1          0        2       1        2
   2          0        1       1        1
   2          0        1       2        1
   2          0        1       1        2    // Duplicate (EditionID)
   2          0        1       2        2

最终结果将根据需要对 editionID 重新编号以使记录唯一。

dateGroup areaGroup itemID editionID aGroups  (EditionID is what is altered)
   1          0        1       1        1
   1          0        1       2        1
   1          0        1       2        2    1 changed to 2 (one more than row 1)
   1          0        2       1        2
   2          0        1       1        1
   2          0        1       2        1
   2          0        1       2        2    1 changed to 2 (one more than row 1)
   2          0        1       2        2

   1          1        1       1
   1          1        1       2
   1          2        1       2             1 changed to 2 (editionID) to match
   1          2        2       1

   2          1        1       1
   2          1        1       2
   2          2        1       2             1 changed to 2 to match above
   2          2        1       2

我知道你可以计算 editionID 像这样的行排名:

select row_number() over ( 
       partition by dateGroup, itemID 
       order by dateGroup, itemID) as editionID

所以我只需要知道如何从一个集合中复制记录

4

3 回答 3

2

对派生表进行交叉连接:(选择 1 作为 aGroups union all select 2)

于 2010-12-17T17:23:33.710 回答
2

I'd create a temporary table with duplicates and their count. Then I'd filter the original table to have only unique rows, and insert another row for each row in the temporary table, incrementing their editionID.

In MySQL, I'd use user @variables; not sure about MS SQL.

于 2010-12-17T17:28:41.277 回答
1

你试过UNION ALL而不是仅仅UNION

UDPATE 也许我误解了这个问题,我认为你遇到了工会丢失副本的问题。

如果问题是你想在联合上做一个 row_number 为什么不做类似的事情

select row_number() over ( 
       partition by dateGroup, itemID 
       order by dateGroup, itemID) as editionID
FROM
(

         SELECT 

              dateGroup, itemID
          FROM TableA
          UNION ALL 
         SELECT 

              dateGroup, itemID
          FROM TableB 
) Data
于 2010-12-17T17:26:34.850 回答