【问题标题】:SQL Server : update table by using when then and using order by clauseSQL Server:使用when then和order by子句更新表
【发布时间】:2021-03-03 16:21:19
【问题描述】:

尝试根据优先级更新子优先级,如果优先级为 1,则所有子优先级应根据优先级增加 +1,其中在更新子优先级时还需要顺序

我已经在 MySql 中尝试了以下查询,它按预期工作,但相同的查询在 SQL Server 中不起作用;我在THEN 条件中使用的表达式在 SQL Server 中不起作用。

SET @p1=0;
SET @p2=0;
SET @P3=0;

UPDATE line_distro_dtl 
SET dc_sub_priority = 
    CASE 
        WHEN (dc_priority =1) THEN (select @p1 := @p1 + 1)
        WHEN (dc_priority =2) THEN (select @p2 := @p2 + 1) 
        WHEN (dc_priority =3) THEN (select @p3 := @p3 + 1) 
    END
WHERE dc_number = 6336 
ORDER BY dc_priority ASC, future_sales DESC;

在 SQL Server 中,我声明了@p1,因为我们必须声明标量变量:

Declare @p1 int;
Declare @p2 int;
Declare @p3 int;
SET @p1=0;
SET @p2=0;
SET @P3=0;

如何在SQL Server 2019中实现上述查询?

【问题讨论】:

  • 请提供样本数据、期望的结果以及您想要的逻辑解释。

标签: sql sql-server azure-sql-database


【解决方案1】:

我认为你想要:

with toupdate as (
      select ld.*,
             row_number() over (partition by dc_priority order by future_sales desc) as seqnum
      from line_distro_dtl
      where dc_number = 6336
     )
update toupdate
    set dc_sub_priority = seqnum;

这会为每个优先级的6336 的子优先级分配一个序列号。

【讨论】:

  • 完美,谢谢 Gordon,您的解决方案对我很有帮助。
猜你喜欢
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多