TSQL - 基于第二个表中两个整数之间的值进行更新。

时间:2017-07-05 21:59:07

标签: sql tsql ssms

使用数百万行进行批量更新时遇到问题。我在下面尝试做的例子。尽可能避免使用案例陈述,因为有超过1000个等级。

表1:

id, score, rank
1   4090   null
2   6400   null
3   8905   null
4   2551   null

表2:

Rank,  Score
 1      0
 2      1000
 3      3500
 4      5000
 5      8000
 6      10000

我正在尝试更新表1以显示正确的排名 EX:得分为6400的ID 2将高于5000但低于8000因此为等级4.这是否可能没有案例陈述?

2 个答案:

答案 0 :(得分:0)

您可以使用cross apply

update t1
    set rank = t2.rank
    from table1 t1 cross apply
         (select top 1 t2.*
          from table2 t2
          where t2.score <= t1.score
          order by t2.score desc
         ) t2;

对于数百万行,我建议使用以下其中一种:

  • 批量更新。
  • 使用case声明。
  • 将输出放在新表中,截断原始表并重新加载

&#34;百万&#34;更新通常是一项非常昂贵的操作。

答案 1 :(得分:0)

另一个选项是与Lead()

一起使用简单的JOIN

示例

Update Table1 Set Rank=B.Rank
 From  Table1 A
 Join  (
            Select Rank
                  ,R1=Score
                  ,R2=Lead(Score,1,999999) over (Order By Score)
             From Table2
       ) B on A.score >= B.R1 and A.Score < B.R2 

<强>返回

id  score   rank
1   4090    3
2   6400    4
3   8905    5
4   2551    2