我有一个包含两列的表,其中没有任何列是唯一的。我需要number为每个用户分别自动增加列。
user | number
1 | 1
2 | 1
1 | 2
3 | 1
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一想法是搜索最后使用的数字并手动加一。有没有更有效的方法?
代替number字段,您可以auto increment在表中创建一个字段(我称之为id),并number通过查询获得所需的字段:
首先添加id:
alter table table_name add id int not null IDENTITY(1,1)
Run Code Online (Sandbox Code Playgroud)
您不再需要数字字段:
alter table table_name drop column number
Run Code Online (Sandbox Code Playgroud)
要获取的查询number(您可以使用它来创建视图):
select user,
row_number() over(partition by user order by id) as number
from table_name
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
636 次 |
| 最近记录: |