2017-03-02 45 views
0

我想弄明白這一點。我有一張有幾十萬行的桌子。每個作業#大約有8行。我需要根據另一列的最高值爲每個作業#更新一列。其中oper_num是最大更新許多行 - 每組一行

enter image description here

作業的cntrl_point需要設置爲1。

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會更合適,但我不知道該怎麼做。

任何幫助將不勝感激。

+0

有可能爲同一'job'值,在'oper_num'列2個或更多相同的最大值? –

回答

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; 
+0

謝謝你的回答。這會更新序列中的第一行,但不會更新oper_num具有最大值的那一行。 –

+0

我可能有這個; –

+0

UPDATE一個 SET a.cntrl_point = 1 FROM jobroute一個 INNER JOIN ( \t SELECT作業,MAX(oper_num)作爲MAXOPERNUM \t FROM jobroute \t GROUP BY工作 \t --HAVING MAX( )B關於a.job = b.job和a.oper_num = b.MAXOPERNUM –