2014-07-25 150 views
0

我想更新一個名爲hours的列,其中每個工作記錄的操作編號在39之前。每項工作都由許多操作組成,最終操作始終爲39號。例如,一項工作可能有一項操作30,31,32,35和最終39或另一項工作可能有30,31和39。每種情況下它只是39之前需要更新的操作,在這種情況下是35和31.SQL更新記錄低於最大值

我設法得到一個選擇腳本來列出每個作業編號的最大但一個操作編號,但無法派生更新版本以更新每個匹配記錄的「小時」。

SELECT jrt.job, max(jrt.oper_num) AS oper_num 
FROM jrt_sch jrt 
INNER JOIN job j ON j.job = jrt.job 
WHERE j.type = 'S' AND jrt.job IN 
       (SELECT jrt.job 
       FROM jrt_sch jrt 
       INNER JOIN job j ON j.job = jrt.job 
       WHERE j.type = 'S' 
       GROUP BY jrt.job 
       HAVING max(jrt.oper_num) = 39) 
     AND oper_num < 39 
GROUP BY jrt.job 

這給

job oper_num 
    2109 31 
    2424 32 
    2509 32 
    2546 31 
    2418 31 
    3972 31 
+0

什麼是您的數據庫引擎? –

回答

0

對待你上面的查詢作爲派生表,加入到它的「工作」和更新記錄的「小時」裏oper_num =您的派生表oper_num 。根據您的數據庫產品,它應該看起來像這樣:

UPDATE js 
SET hours='some value' 
FROM jrt_sch js 
INNER JOIN (
    <Your Query Above> 
) m 
    ON js.job=m.job 
    AND js.oper_num=m.oper_num