在组内生成序列

798qvoo8  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(324)

如果我有如下数据:

pkey, category, group_id
1,       a,      NULL
2,       a,      NULL
3,       a,      NULL
4,       b,      NULL
5,       b,      NULL
6,       b,      NULL

如何用为每个类别重置的序列号替换空值?
得到:

pkey, category, group_id
1,       a,      1
2,       a,      2
3,       a,      3
4,       b,      1
5,       b,      2
6,       b,      3

谢谢

3pvhb19x

3pvhb19x1#

你可以用 row_number() :

select t.*, row_number() over (partition by category order by pkey) as group_id
from t;

你可以把这个包含在 update 如果确实要更改数据:

update t
    set group_id = tt.new_group_id
    from (select t.*, row_number() over (partition by category order by pkey) as new_group_id
          from t
         ) tt
    where tt.pkey = t.pkey;
zrfyljdw

zrfyljdw2#

你可以用 ROW_NUMBER :

SELECT
    pkey,
    category,
    ROW_NUMBER() OVER (PARTITION BY category ORDER BY pkey) group_id
FROM yourTable
ORDER BY
    pkey;

演示

相关问题