更新许多行 - 每组一行

时间:2017-03-02 14:35:07

标签: sql sql-server-2008 sql-update

我想弄明白这一点。我有一张有几十万行的桌子。每个作业#大约有8行。我需要根据另一列的最高值为每个作业更新一列#。

enter image description here

对于作业,cntrl_point需要设置为1,其中oper_num最大。

UPDATE jobroute
SET cntrl_point = 1
SELECT DISTINCT job, cntrl_point, MAX(oper_num) OVER (PARTITION BY job) MAX_Oper_Num
FROM jobroute
WHERE job not like 'J%' AND suffix = 0 

我认为我在OVER PARTITION中使用不正确。我想也许CURSOR会更合适,但我不知道该怎么做。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在SQL Server中,您可以使用row_number()

with toupdate as (
      select jr.*, row_number() over (partition by job order by oper_num desc) as seqnum
      from jobroute jr
      where job not like 'J%' AND suffix = 0 
     )
UPDATE toupdate
    SET cntrl_point = 1
    WHERE seqnum = 1;