2015-11-01 92 views
1

有關如何將批號生成到SQL Server表中的batch_number列(從1到3)的任何想法,並再次重複它,如下面的腳本中所示?如何在SQL Server中生成批號

在此先感謝

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 

回答

-1
update @mTestTable 
set batch_number = (id-1) % 3 + 1 

如果ID不會是連續的,那麼其中一種方法是使用光標通過它做的事。只需對各行進行逐一計數,然後update即可得到相應的批號。

+0

'ID%3'當'= 0'和'id'否則? –

1

使用row_number()和一些算術:

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;