简体   繁体   English

基于分组添加和更新具有顺序编号的列

[英]Add and update a column with sequential numbering based on grouping

I have a table with following structure我有一个具有以下结构的表

Id ID Division分配 Details细节
1 1 A一个 some text一些文字
2 2 A一个 some text一些文字
3 3 B some text一些文字
4 4 B some text一些文字
5 5 B some text一些文字

I need to add a new column of integer type named "Order" with some data as described below:我需要添加一个名为“Order”的 integer 类型的新列,其中包含如下所述的一些数据:

Id ID Division分配 Details细节 Order命令
1 1 A一个 some text一些文字 1 1
2 2 A一个 some text一些文字 2 2
3 3 B some text一些文字 1 1
4 4 B some text一些文字 2 2
5 5 B some text一些文字 3 3

As we can see integer data in "Order" column sequence has to be reset if "Division" data changes.正如我们所见,如果“除”数据发生变化,则必须重置“订单”列序列中的 integer 数据。 There's are thousand of rows in the table, with more than 100 different divisions.表中有数千行,有 100 多个不同的分区。

How can I achieve this?我怎样才能做到这一点?

You can use row_number() :您可以使用row_number()

select t.*, 
    row_number() over(partition by division order by id) rn
from mytable t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM