按顺序分配行的最便宜的方法

Cheapest way to assign rows in order of sequence

我有一个项目,其中有一个条形码列表,我需要将它们相关联以根据第二列以正确的顺序记录数字。

我的数据是这样的:

Coupon Code  |  Code Type | Sequence
1234567890   |     1      |  NULL
9876543210   |     1      |  NULL
5464654222   |     2      |  NULL
4554222558   |     3      |  NULL
5464622154   |     3      |  NULL
5688979465   |     3      |  NULL

然后我有另一组数据是这样的:

Sequence  |   Code Type
    1     |      3
    2     |      3
    3     |      1
    4     |      2
    5     |      1
    6     |      3

是否有任何便宜的方法来连接这两个数据集,以便我可以根据第二个分配第一个 table 中的序列?只要是正确的条码类型,首先分配哪个条码真的是任意的。我已经做了一个游标,它太慢了。

有什么建议吗?我可以做我自己的研究,只要有人指出我正确的方向就会有很大的帮助。抱歉格式不正确。

如果我没理解错你可以使用row_number():

select t1.*, t2.sequence
from (select t1.*,
             row_number() over (partition by code_type order by couponcode) as seqnum
      from table1 t1
     ) t1 join
     (select t2.*,
             row_number() over (partition by code_type order by sequence) as seqnum
      from table2 t2
     ) t2
     on t1.code_type = t2.code_type and t1.seqnum = t2.seqnum;

如果您需要分配值,可以将此类逻辑合并到 update 中。但是,其语法取决于您使用的数据库。

编辑:

SQL 服务器中的更新为:

update t1
    set t1.sequence = t2.sequence
from (select t1.*,
             row_number() over (partition by code_type order by couponcode) as seqnum
      from table1 t1
     ) t1 join
     (select t2.*,
             row_number() over (partition by code_type order by sequence) as seqnum
      from table2 t2
     ) t2
     on t1.code_type = t2.code_type and t1.seqnum = t2.seqnum;