【问题标题】:Cheapest way to assign rows in order of sequence按顺序分配行的最便宜方法
【发布时间】:2020-12-21 15:12:45
【问题描述】:

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

我的数据如下所示:

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

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

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

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 这是一个 sql 2012 服务器。不知道如何标记。
  • 你的意思是 标签用于 SQL language 相关问题。
  • 感谢您添加正确的标签,现在正在尝试您的答案

标签: sql sql-server join sql-server-2012


【解决方案1】:

如果我理解正确你可以使用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 Server 中的更新将是:

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;

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 2015-07-08
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多