TSQL用于从tableB更新TABLEA,其中不存在id

时间:2015-11-25 03:46:07

标签: sql-server tsql duplicates

我有以下表结构。

Table A
InvoiceNumber
InvoiceDate
Sku
SerialNumber

Table B
InvoiceNumber
Invoicedate
Sku
SerialNumber

表B具有有效的SerialNumbers,而表A没有(其空白)。我想用表B的序列号更新表A.

可以有多个具有相同invoiceNumber,Invoicedate和Sku的记录,只有serialNumber是唯一的。

如果我做了

update tablea set serialNumber = tableb.serialNumber
where tablea.sku = tableb.sku
and tablea.invoicenumber = tableb.invoicenumber
and tablea.invoicedate = tableb.invoicedate

我最终在表a中获得了重复的连续剧。

样本数据

表a

InvoiceNbr : 1 invoiceDate = 10/01/2015 sku = ABC serial = blank
InvoiceNbr : 1 invoiceDate = 10/01/2015 sku = ABC serial = blank

表b

InvoiceNbr : 1 invoiceDate = 10/01/2015 sku = ABC serial = abc
InvoiceNbr : 1 invoiceDate = 10/01/2015 sku = ABC serial = xyz

无论我做什么,我总是在表a中使用dupes:|

1 个答案:

答案 0 :(得分:0)

试试这个:

update tableA
set serialNumber = b.serialNumber
from (select *, row_number() over (partition by invoicenumber, invoicedate, sku order by serialnumber) rn from tableA) a
inner join
(select *, row_number() over (partition by invoicenumber, invoicedate, sku order by serialnumber) rn from tableB) b 
on a.sku = b.sku and a.invoicenumber = b.invoicenumber and a.invoicedate = b.invoicedate and a.rn = b.rn

Demo

如果我理解正确,表B中有记录,除了serialNumber之外的所有列具有相同的值,并且您当前的更新逻辑只使用serialNumber的值之一填充表A而不是1到1更新。上述解决方案使用row_number为表B中的每一行创建一个额外的标识符,然后将其用作匹配行以进行更新的附加条件。