Oracle - 使用内部联接和分区进行更新?

时间:2013-07-30 18:45:46

标签: sql join oracle11g sql-update

我的表格如下所示,名为HIST:

+---------------+---------------+----------------+-------------+-------------+
|      ID       |    MGROUP     |  ACTIVESTATUS  |  FROM_DATE  |   TO_DATE   |
+---------------+---------------+----------------+-------------+-------------+
|  86183752530  |  30546        |  Inactive      |  09-MAR-09  |  05-SEP-09  |
|  86183752533  |  30546        |  Active        |  05-SEP-09  |  29-SEP-09  |
|  86183752534  |  30546        |  Inactive      |  29-SEP-09  |  (null)     |
|  86369271439  |  85764511006  |  Active        |  19-OCT-10  |  (null)     |
|  86369271447  |  85851006389  |  Active        |  16-NOV-10  |  (null)     |
|  86369271517  |  86369271513  |  Active        |  25-JAN-11  |  (null)     |
+---------------+---------------+----------------+-------------+-------------+

此表用于记录组的历史记录。例如,我们可以看到MGROUP 30546于09年3月9日至09年9月9日失效,然后在05-SEP-09至29-SEP-09再次活跃。然后终于在29-SEP-09再次进入Inactive状态,目前这种方式直到任何未来的更新(null)。

现在我有另一个看起来如下的表:GROUP:

+-------------------+-------------+--------------+
|      M_NAME       |     ID      | ACTIVESTATUS |
+-------------------+-------------+--------------+
| Jack Smith        |       30546 | Inactive     |
| John Doe          | 85764511006 | Active       |
| Bobby Drop Tables | 85851006389 | Active       |
+-------------------+-------------+--------------+

我写了一个Select Statement,它做了我想做的事情:

    select
    m_name,
    hist.to_date,
    SYSDATE AS new_hist_to_date
    from group
    inner join
    (
        select 
        mgroup, 
        from_date, 
        to_date,  
        rowNumber
        from 
        (
          select 
          mgroup, 
          from_date, 
          to_date, activestatus, row_number() over ( partition by mgroup order by to_date desc nulls first) rowNumber
          from hist
        )
        where rowNumber = 1
    ) hist ON hist.MGROUP = group.id
where m_mgroup.ACTIVESTATUS = "Inactive"

我将此转换为更新语句的任何尝试都失败了。我想要做的是将表HIST.TO_DATE设置为SYSDATE,如果表GROUP.ACTIVESTATUS = Inactive。

这样做的好方法是什么?

1 个答案:

答案 0 :(得分:1)

最懒的方法是从查询中选择rowid,并执行以下操作:

UPDATE hist SET ....
WHERE rowid IN (  your query )

我创建了SQLFiddle demo来证明这一点。

查询可能如下所示:

UPDATE hist
set to_date = sysdate
where rowid in (
    select hist_rowid 
 from (       
        select rowid hist_rowid,
        mgroup, 
        from_date, 
        to_date,  
        rowNumber
        from 
        (
          select 
          mgroup, 
          from_date, 
          to_date, activestatus, row_number() over ( partition by mgroup order by to_date desc nulls first) rowNumber
          from hist
        )
        where rowNumber = 1
  ) hist
  join "GROUP" ON hist.MGROUP = "GROUP".id AND "GROUP".ACTIVESTATUS = 'Inactive'
);

GROUP是Oracle中的保留字,所以我用“”包围GROUP表的名称以避免语法错误