使用游标更新包含来自另一列的值的列

时间:2014-05-27 18:08:37

标签: sql database oracle plsql

我有一个包含2列tablecolumn1的表column2。我正在执行以下查询以获取所有重复的行并枚举每组重复行中的行:

CURSOR c
    IS
      SELECT groupnum,
             column1,
             column2,
             seqnum
        FROM (SELECT t.*,
                     COUNT (*) OVER (PARTITION BY column1, column2)
                         AS cnt,
                     DENSE_RANK () OVER (ORDER BY column1, column2)
                         AS groupnum,
                     ROW_NUMBER ()
                     OVER (PARTITION BY column1, column2
                           ORDER BY column1)
                         AS seqnum
                FROM table) t
       WHERE cnt > 1
    ORDER BY groupnum;

对于具有这些值的表table

+------------+---------+
| COLUMN1    | COLUMN2 |
+------------+---------+
| a          | x       |
| a          | x       |
| o          | o       |
| o          | o       |
+------------+---------+

光标将检索此数据:

+----------+------------+------------+--------+
| GROUPNUM | COLUMN1    | COLUMN2    | SEQNUM |
+----------+------------+------------+--------+
| 1        | a          | x          | 1      |
| 1        | a          | x          | 2      |
| 2        | o          | o          | 1      |
| 2        | o          | o          | 2      |
+----------+------------+------------+--------+

我的目标是从列SEQNUM中选择每个值,并更新表column1table列中的对应字段:

+------------+---------+
| COLUMN1    | COLUMN2 |
+------------+---------+
| a1         | x       |
| a2         | x       |
| o1         | o       |
| o2         | o       |
+------------+---------+

我尝试了一个游标FOR循环,但我无法弄清楚如何建立column1和每个SEQNUM中每个字段之间的对应关系。

1 个答案:

答案 0 :(得分:1)

您需要找到识别每条记录的方法。最简单的方法是使用rowid(我们在oracle中,对吗?):

 select rowid, 
 DENSE_RANK () OVER (ORDER BY column1, column2) groupnum
 column1, column2, ROW_NUMBER () OVER 
 (PARTITION BY column1, column2 ORDER BY rowid) seqnum
 from table1
 where (column1, column2) in 
 (select column1, column2 
 from table1 
 group by column1, column2 
 having count(*) > 1)

我修改了你的查询(我的groupnum与你的不同,因为我不计算唯一的组),我的seqnum是稳定的,不会在运行之间改变。

因此,为了进行更新,我将上面的查询加入table1 by rowid。