0

私のSQLデータは次のようになります。

Col1
A
A
A
B
B
C
D

一意の値のみにキーを追加したい。したがって、最終結果は次のようになります。

Col1  Col2
A       1
A       1
A       1
B       2
B       2
C       3
D       3

これどうやってするの?

4

1 に答える 1

5

dense_rank()ウィンドウ関数でこれを行うことができます:

select col1, dense_rank() over (order by col1) as col2
from t;

これにより、クエリとして問題が解決されます。実際にテーブルを変更したい場合、コードは次のようになります。

alter table t add col2 int;

with toupdate as (
    select t.*, dense_rank() over (order by col1) as newcol2
    from t
)
update toupdate
    set col2 = newcol2;
于 2013-09-16T01:01:52.057 に答える