Postgres排序复合键

时间:2016-04-04 10:13:32

标签: sql postgresql

我的table_a包含列product_id,store_id,x。

我想

create table_b as
select store_id, product_id, sequence_number
from table_a

sequence_number是自动生成的数字,应该如下所示:

store_id            |   product_id              |   sequence_number
1                   |   1                       |   1
1                   |   1                       |   2
1                   |   1                       |   3
1                   |   2                       |   1
1                   |   2                       |   2
2                   |   1                       |   1
2                   |   1                       |   2

是否可以使用sql查询执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以使用row_number()

执行此操作
create table_b as
    select store_id, product_id,
           row_number() over (partition by store_id, product_id
                              order by NULL
                             ) as sequence_number
    from table_a;