0

これは、数値が増加する条件を満たすPostgres Update レコードに関するこの質問の複製ですが、SQLite3 で動作する方法が必要です。

元の質問からの抜粋:

をちょきちょきと切る

次のようなpostgresのテーブルがあります:

Id    Name    local_site_id    local_id
1     A       2                
2     B       2
3     C       1
4     D       2
5     E       1

SQLクエリを使用してテーブルをこれに更新するにはどうすればよいですか:

Id    Name    local_site_id    local_id
1     A       2                1
2     B       2                2
3     C       1                
4     D       2                3
5     E       1                

現在、local_id フィールドはすべてのレコードで空です。local_site_id=2Is it possible using SQL?を持つ行に対してのみ、1 から始まる増分番号で local_id 値を更新したい

エンドスニップ

そこの回答からこのコマンドを試しましたが、SQLite3では機能しません

update T set local_id=s.rn 
from (select id,row_number() over(order by id) as rn from T where local_site_id=2) s
where T.id=s.id;

SQLite3でこれを達成するにはどうすればよいですか?

4

2 に答える 2

1

これはそれを行う必要があります:

.mode column
.headers on

create table T (Id, Name, local_site_id, local_id);

insert into T values
    (1, 'A', 2, null),
    (2, 'B', 2, null),
    (3, 'C', 1, null),
    (4, 'D', 2, null),
    (5, 'E', 1, null);

update T set local_id = (
    select 
        case local_site_id
            when 2 then (select count(*) 
                         from T t2 
                         where t2.id <= t1.id and local_site_id=2)
            else null
        end
    from T as t1 where T.id=t1.id);

select * from T;

戻り値:

Id          Name        local_site_id  local_id  
----------  ----------  -------------  ----------
1           A           2              1         
2           B           2              2         
3           C           1                        
4           D           2              3         
5           E           1                        
于 2012-08-30T14:48:07.433 に答える
0

私は自分で方法を見つけました。一時テーブルを作成し、一時テーブルの「ROWID」内部列を使用して元のテーブルを更新しました。

create table temptable as select id from tablename where local_site_id=2;

update tablename 
    set local_id=(select ROWID from temptable where temptable.id=tablename.id)
    where exists (select ROWID from temptable where temptable.id=tablename.id);

しかし、新しいテーブルを作成する必要がないため、Ludo の回答を受け入れます。

于 2012-08-30T15:05:45.920 に答える