更新唯一表SQL

时间:2017-07-07 22:35:11

标签: sql oracle exists

你好,我有这张桌子。

ADDR      | STATE  |  ID 
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |   (null)
CRA.20 15 |  PRI   |   RR_88_JK

我需要转换这个表..

ADDR      | STATE |   ID 
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  PRI  |   RR_88_JK

我有这个QRY但没有功能。你有一个想法吗?。

UPDATE TABLE_A A
   SET a.ID = b.ID
 WHERE EXISTS
           (SELECT b.ID
              FROM TABLE_A B
             WHERE a.ADDR = B.ADDR  AND b.STATE = 'PRI')
 and  A.STATE = 'REP';

感谢。

2 个答案:

答案 0 :(得分:1)

您需要子查询来设置值:

UPDATE TABLE_A A
   SET a.ID = (SELECT b.ID
               FROM TABLE_A B
               WHERE a.ADDR = B.ADDR AND b.STATE = 'PRI' AND rownum = 1
              )
   WHERE EXISTS (SELECT b.ID
                 FROM TABLE_A B
                 WHERE a.ADDR = B.ADDR AND b.STATE = 'PRI'
                ) AND
         A.STATE = 'REP';

B仅在子查询中已知,而不在外部查询中。

答案 1 :(得分:1)

以下将做你想做的事:

UPDATE TABLE_A A
   SET a.ID = (SELECT MIN(ID)
                 FROM TABLE_A
                 WHERE ID IS NOT NULL AND
                       STATE = 'PRI')
   WHERE ID IS NULL AND
         STATE = 'REP'

祝你好运。