如何在SQL Server中生成批次号

如何在SQL Server中生成批次号,sql,sql-server,row-number,Sql,Sql Server,Row Number,您知道如何在SQL Server表中从1到3生成批次号到batch\u number列,并按照脚本中的如下所示再次重复吗 提前谢谢 Declare @mTestTable table ( id int, city varchar(50), batch_number int ) --Insert some sample data Insert into @mTestTable values (1, 'London') Insert into @mTestTable

您知道如何在SQL Server表中从1到3生成批次号到
batch\u number
列,并按照脚本中的如下所示再次重复吗

提前谢谢

Declare @mTestTable table
(
     id int,
     city varchar(50),
     batch_number int
)

--Insert some sample data
Insert into @mTestTable values (1, 'London')
Insert into @mTestTable values (2, 'Karachi')
Insert into @mTestTable values (3, 'New York')
Insert into @mTestTable values (4, 'Melbourne')
Insert into @mTestTable values (5, 'Beijing')
Insert into @mTestTable values (6, 'Tokyo')
Insert into @mTestTable values (7, 'Moscow')
我需要生成从1到3的批号,然后再次重复

Id  City        Batch_Number
1   London      1
2   Karachi     2
3   New York    3
4   Melbourne   1
5   Beijing     2
6   Tokyo       3
7   Moscow      1
如果ID不是连续的,那么一种方法是使用光标通过它。只需逐个计算行数,并更新相应的批号。

使用
行数()
和一些算术:

with toupdate as (
      select t.*, 1 + ((row_number() over (order by id) - 1) % 3) as new_batch_no
      from testtable
     )
update toupdate
    set batch_number = new_batch_number;

id%3
当它是
时=0
id
是否为其他?
with toupdate as (
      select t.*, 1 + ((row_number() over (order by id) - 1) % 3) as new_batch_no
      from testtable
     )
update toupdate
    set batch_number = new_batch_number;