tsql - 设置顺序值而不循环/游标
我需要在数据表中设置一个非唯一标识符。这在组内是连续的,即。对于每个组,ID 应从 1 开始,并以 1 为增量递增,直到该组的最后一行。
下表对此进行了说明。 “新 ID”是我需要填充的列。
Unique ID Group ID New ID
--------- -------- ------
1 1123 1
2 1123 2
3 1124 1
4 1125 1
5 1125 2
6 1125 3
7 1125 4
有没有什么方法可以在不循环/游标的情况下做到这一点?如果循环/游标是唯一的方法,那么最有效的代码是什么?
谢谢
I need to set a non-unique identifier in a data table. This would be sequential within a group ie. for each group, the ID should start at 1 and rise in incremements of 1 until the last row for that group.
This is illustrated by the table below. "New ID" is the column I need to populate.
Unique ID Group ID New ID
--------- -------- ------
1 1123 1
2 1123 2
3 1124 1
4 1125 1
5 1125 2
6 1125 3
7 1125 4
Is there any way of doing this without looping/cursoring? If looping/cursoring is the only way, what would the most efficient code be?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一种方法是在带有子查询的
UPDATE...FROM
语句中使用ROW_NUMBER() OVER(PARTITION BY ... ORDER BY ...)
/code> 在FROM 子句
中。One method is to use
ROW_NUMBER() OVER(PARTITION BY ... ORDER BY ...)
in anUPDATE...FROM
statement with asubquery
in theFROM clause
.我同意 Damien 在评论中的观点,但您不需要
JOIN
您可以直接更新 CTE。在线演示
I agree with Damien's point in the comments but you don't need a
JOIN
you can just update the CTE directly.Online Demo
如果您使用的是 SS 2000,请替换为 RowNumber()
Alternate to RowNumber() if you're on SS 2000
如果您运行的是旧版本的 mssql,此解决方案也适用
This solution will also work, if you are running an old version of mssql