最大的Oracle查询(日期)

时间:2017-09-17 17:19:46

标签: sql oracle update-statement

我的目标是创建一个查询,然后创建一个更新语句,将CI字段更新为“1”,但仅当max(vt_end)小于sysdate AND 时才会已经更新了该特定代码的最大值(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.

1 个答案:

答案 0 :(得分:0)

您正在使用MAX()但是您需要使用EXISTS,因为使用MAX()可以混合来自不同行的值,我想您需要使用{{1}进行更新}和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_ENDCODE获得最大值,则会返回每个VT_END最多'31-dec-9999'的行日期和NOT EXIST (...)过滤掉已更新的行。