oracle 更新派生表的结果

toe95027  于 2023-08-04  发布在  Oracle
关注(0)|答案(1)|浏览(97)

只是想问一下,是否可以更新派生表的结果。
我的代码如下:

UPDATE FROM (select a.*, row_number() over
 (partition by device_util_id 
  order by service_point_util_id, install_date desc) as rownum   
from eadwstage.test_device_locations a) tst
set DELTA_FLAG = 'D'
where tst.rownum <> 1

字符串
我的查询抛出了无效的SQL语句。
我还尝试在WHERE条件中添加DeviceID,但它将两个ID都更新为'D'
样本数据为:

+----------+-------------+---------------+------------+
| DeviceID |    Location |    DELTA_FLAG |     ROWNUM |
+----------+-------------+---------------+------------+
|  1       |          US |              I|          1 |
|  1       |          UK |              U|          2 |
|  2       |          MY |              I|          1 |
|  3       |          JP |              I|          1 |
+----------+-------------+---------------+------------+


基本上,我想将rownum > 1的记录更新为'D' Delta_Flag。
下面是我想要的:

+----------+-------------+---------------+------------+
| DeviceID |    Location |    DELTA_FLAG |     ROWNUM |
+----------+-------------+---------------+------------+
|  1       |          US |              I|          1 |
|  1       |          UK |              D|          2 |
|  2       |          MY |              I|          1 |
|  3       |          JP |              I|          1 |
+----------+-------------+---------------+------------+

  • 注意:ROWNUM列不是表的一部分

数据库是Oracle或Teradata

uemypmqf

uemypmqf1#

UPDATE FROM不是有效的Oracle SQL语法。
在Oracle中,可以使用相关子查询(在ROWID伪列上进行相关):

UPDATE eadwstage.test_device_locations
SET DELTA_FLAG = 'D'
WHERE ROWID IN (
  SELECT ROWID
  FROM   (
    SELECT ROW_NUMBER() OVER (
             PARTITION BY device_util_id 
             ORDER BY service_point_util_id, install_date DESC
           ) AS rn
    FROM   eadwstage.test_device_locations
  )
  WHERE  rn > 1
);

字符串
或者MERGE语句:

MERGE INTO eadwstage.test_device_locations dst
USING (
  SELECT ROW_NUMBER() OVER (
           PARTITION BY device_util_id 
           ORDER BY service_point_util_id, install_date DESC
         ) AS rn
  FROM   eadwstage.test_device_locations
) src
ON (src.ROWID = dst.ROWID AND src.rn > 1)
WHEN MATCHED THEN
  UPDATE
  SET delta_flag = 'D';

相关问题