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