0

我的目标是创建一个查询,然后创建一个更新语句,它将 CI 字段更新为“1”,但前提是 max(vt_end) 小于 sysdate并且只有当 max(vt_end) 没有更新记录时该特定代码的 31-dec-9999。我在下面有我的基本查询,但我不确定如何仅识别要更新的那些记录。

SELECT CODE,
     MAX (VT_END),
     TT_STOP,
     MOST_RECENT_IND AS MRI,
     CURRENT_IND AS CI
FROM TABLE
WHERE TT_STOP > SYSDATE AND CODE IN ('0001F', '0001M', '0001T')
GROUP BY CODE,
     VT_END,
     MOST_RECENT_IND,
     CURRENT_IND
ORDER BY CODE, VT_END


CODE    VT_END       TT_STOP    MRI CI  
0001F   12/31/2004  12/31/9999  0   0  
0001F   12/31/2006  12/31/9999  0   0  
0001F   3/31/2007   12/31/9999  0   0  
0001F   12/31/2007  12/31/9999  0   0  
0001F   12/31/2011  12/31/9999  0   0  
0001F   12/31/2012  12/31/9999  0   0  
0001F   12/31/9999  12/31/9999  1   1  
0001T   12/31/2003  12/31/9999  0   0  
0001T   12/31/2004  12/31/9999  0   0  

我也试过这个查询,但它是错误的,因为它带回了 0001F 12/31/2012 的记录,这是不正确的,因为它已经有一条记录 '31-dec-9999'

SELECT CODE,
     MAX (VT_END),
     MOST_RECENT_IND AS MRI,
     CURRENT_IND AS CI
FROM SRC_PROCDR_DESCRIPTOR_SCD2
WHERE TT_STOP > SYSDATE AND CODE IN ('0001F', '0001M', '0001T')
AND VT_END <> '31-dec-9999'
GROUP BY CODE,
     MOST_RECENT_IND,
     CURRENT_IND
ORDER BY CODE

Incorrect Results:
CODE    VT_END       TT_STOP    MRI CI 
0001F   12/31/2012  0   0
0001T   12/31/2004  0   0

结果应该是

CODE    VT_END       TT_STOP    MRI CI 
0001T   12/31/2004  12/31/9999  0   0   - Update to '1' on CI  
--This should be the only record returned in the above query to put into an 
UPDATE statement.
4

1 回答 1

0

您正在使用MAX(),但您需要使用EXISTS,因为使用MAX()您可以混合来自不同行的值,我想您需要同时使用CODE和更新VT_END

SELECT CODE, VT_END
FROM TABLE1
WHERE TT_STOP > SYSDATE
  AND CODE IN ('0001F', '0001M', '0001T')
  AND VT_END <> '31-dec-9999'
  AND NOT EXISTS(SELECT * FROM TABLE1 T1
    WHERE T1.CODE=TABLE1.CODE -- join condition
      AND T1.VT_END>TABLE1.VT_END) -- filter condition
ORDER BY CODE

仅当最大值不是时,这将返回VT_END每个具有最大值的行(您获得最大日期并过滤掉已更新的行)。CODEVT_END'31-dec-9999'NOT EXIST (...)VT_END <> '31-dec-9999'

于 2017-09-17T18:18:46.763 回答