2017-04-07 27 views
0

我有一个包含父表记录子集的表。 每个子集都有一个存储在[rank]字段中的订单。 我需要根据字段otherRank中保存的新订单更新此表中特定子集的此字段。T-SQL - 通过Row_Number()更新记录的子集

执行以下操作盖它:

update mytable t1 set 
[rank] = t2.new_rank_num 
from (select t2.id, new_rank_num = row_number() over (order by t2.otherRank) 
    from mytable t2 where t2.parentID = 628) t2 
where t1.id = t2.id 

,或者将我需要:

update mytable t1 set 
[rank] = t2.new_rank_num 
from (select t2.id, new_rank_num = row_number() over (order by t2.otherRank) 
    from mytable t2 where t2.parentID = 628) t2 
where t1.id = t2.id and t1.parentID = 628 

我的具体问题是,我不希望任何的parentID 628

的职权范围之外的更新

编辑 试图运行此命令时出现错误:

附近t1 不正确的语法不正确的语法附近t2

所以我想语法必须是:

update mytable set 
    [rank] = t2.new_rank_num 
    from (select id, new_rank_num = row_number() over (order by otherRank) 
from mytable where parentID = 628) t2 
where id = t2.id and parentID = 628 

编辑2

OK,我SqlZim推荐使用CTE解决方案。 它看起来像这样:

;with cte as (
    select t2.id, new_rank_num = row_number() over (order by t2.otherRank) 
    from mytable t2 where t2.parentID = 628 
) 

update t1 set 
    [rank] = t2.new_rank_num 
from mytable t1 
inner join cte t2 on t1.id = t2.id 
+2

会发生什么事,当你尝试了吗? –

+0

我承认没有尝试过,因为我主要需要一些关于查询语法的建议。 – scgough

+0

我没有看到任何明显的语法错误。如果它给出了预期的结果,那就去吧。 –

回答

3

我更喜欢使用common table expression (cte)做这样的事情:

;with cte as (
    select * 
    , new_rank_num = row_number() over (
     partition by ParentId 
     order by otherRank 
     ) 
    from mytable 
) 
update cte 
set [rank] = new_rank_num 
where ParentID = 628; 

如果您想预览运行更新前的变化,只是改变上述的select而不是update。请注意,只有cte之后的第一条语句才能使用cte。

+0

谢谢我使用CTE解决方案 - 请参阅更新问题 – scgough

0

您也可以更新视图,而不仅仅是表格。

试试这个:

UPDATE T 
SET [rank] = [new_rank_num] 
FROM (
    SELECT 
     [rank]   = [rank], 
     [new_rank_num] = row_number() over (order by otherRank) 
    FROM mytable 
    WHERE parentID = 628 
) T