任何人都可以帮助我将此MSSQL查询转换为ORACLE吗?

时间:2014-02-05 12:40:00

标签: oracle

这是我的MSSQL查询

UPDATE  YT 
  SET     POSITION = RN 
                  FROM    ( 
                   SELECT  ROW_NUMBER() OVER (PARTITION BY PARENTID ORDER BY ID) - 1 RN 
                  FROM  CONVERTED 
                   ) YT

这是我尝试将其转换为Oracle

UPDATE  CONVERTED 
  SET     POSITION = (SELECT  ROW_NUMBER() OVER (PARTITION BY PARENTID ORDER BY ID) - 1 RN 
                  FROM  CONVERTED 
                   );

很遗憾我收到此错误

SQL Error: ORA-01427: single-row subquery returns more than one row
01427. 00000 -  "single-row subquery returns more than one row"

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

假设id是唯一的,以下内容应该适用于两个数据库:

UPDATE  CONVERTED 
    SET POSITION = (select count(*) - 1
                    from converted c2
                    where c2.parentid = converted.parentid and
                          c2.id <= converted.id
                   );

答案 1 :(得分:0)

可能你正在寻找这样的东西?

SQL> create table t (id int, parentid int, position int)

2 /

SQL> begin
  2  insert into t values(1,null,null);
  3  insert into t values(10,null,null);
  4  insert into t values(3,1,null);
  5  insert into t values(7,1,null);
  6  insert into t values(4,1,null);
  7  insert into t values(19,7,null);
  8  insert into t values(11,7,null);
  9  insert into t values(72,10,null);
 10  insert into t values(42,10,null);
 11  insert into t values(23,10,null);
 12  commit;
 13  end;
 14  /

SQL> merge into t using
  2  (select id, row_number() over (partition by parentid order by id) - 1 rn
  3  from  t) src
  4  on (src.id = t.id)
  5  when matched then
  6    update set t.position = src.rn
  7  /

SQL> select * from t
  2  start with parentid is null
  3  connect by prior id = parentid
  4  order siblings by position
  5  /

        ID   PARENTID   POSITION                                                
---------- ---------- ----------                                                
         1                     0                                                
         3          1          0                                                
         4          1          1                                                
         7          1          2                                                
        11          7          0                                                
        19          7          1                                                
        10                     1                                                
        23         10          0                                                
        42         10          1                                                
        72         10          2