2016-12-09 4 views
0

次のOracleデータベーステーブルを考える:Oracle表の列の値をどのようにシフトダウンしますか?

 
group revision comment 
1  1   1    
1  2   2 
1  null  null 
2  1   1    
2  2   2 
2  3   3 
2  4   4 
2  null  null 
3  1   1    
3  2   2 
3  3   3 
3  null  null 

私は、次の表を取得するように、そのグループ内で、バージョンに関連して1つのステップダウンコメント欄をシフトしたい:

 
group revision comment 
1  1   null    
1  2   1 
1  null  2 
2  1   null    
2  2   1 
2  3   2 
2  4   3 
2  null  4 
3  1   null    
3  2   1 
3  3   2 
3  null  3 

これのほとんどは(まだリビジョン= 1をカバーするために別のクエリを必要とする)ん

    

    MERGE INTO example_table t1 
    USING example_table t2 
    ON (
     (t1.revision = t2.revision+1 OR 
     (t2.revision = (
      SELECT MAX(t3.revision) 
      FROM example_table t3 
      WHERE t3.group = t1.group 
     ) AND t1.revision IS NULL) 
    ) 
    AND t1.group = t2.group) 
    WHEN MATCHED THEN UPDATE SET t1.comment = t2.comment; 

が、それは非常に遅いです:私は、次のクエリを持っています。

私の質問は、できるだけ効率的にMaxを使用して、各グループの最高リビジョンを引き出す方法です。

答えて

2

私はこれが動作しているようですうんlagないmax

create table example_table(group_id number, revision number, comments varchar2(40)); 
insert into example_table values (1,1,1); 
insert into example_table values (1,2,2); 
insert into example_table values (1,3,null); 
insert into example_table values (2,1,1); 
insert into example_table values (2,2,2); 
insert into example_table values (2,3,3); 
insert into example_table values (2,4,null); 

select * from example_table; 

merge into example_table e 
using (select group_id, revision, comments, lag(comments, 1) over (partition by group_id order by revision nulls last) comments1 from example_table) u 
on (u.group_id = e.group_id and nvl(u.revision,0) = nvl(e.revision,0)) 
when matched then update set comments = u.comments1; 

select * from example_table; 
+1

を使用します。 これは、このhttp://docs.oracle.com/cd/B28359_01/server.111/b28286/functions001.htm#SQLRF06174(分析関数のセクション)と相まって、私の多くを助けました。 –

+0

UPDATEステートメントは機能しません。WITH句はUPDATEの前に指定できません。また、MERGEでのON状態でのNVLの使用は危険です.0が正当な値のリビジョンの1つであればどうでしょうか? "またはu.revisionがnullで、v.revisionがnullです"と書く方が良いです。 (実際には、テーブルにプライマリキーがあればさらに良いでしょう!)そうでなければ、これは正しい答えです、良い仕事です! – mathguy

+0

@mathguyはもちろんありません。答えを築くのは私の混乱でした。適切な答えは、更新ではなくマージです。 – Kacper

関連する問題