使用窗口功能/分析功能,如
Row_number() over (partition by Nic, order by ID)
SQL Fiddle 喜歡的東西...
UPDATE B
SET B.Nic = C.NewNic
FROM Foo B
INNER JOIN (SELECT ID, NIC + '-' + cast(Row_number()
over (partition by NIC order by ID) as varchar(20)) as newNic
FROM FOo) C
on C.ID = B.ID
這會給你
id = 567 , nic= '786-786-1'
id = 788 , nic = '786-786-2'
id = 2344, nic = '786-786-3'
你總是能做個案陳述和當行1,則不會顯示再減去1,如果你要離開,沒有一個-1
SQL Fiddle getting rid of the -1 for first record...
UPDATE B
SET B.Nic = Case WHEN C.RN = 1 then B.Nic Else B.Nic+ '-'+cast((RN-1) as varchar(20)) end
FROM Foo B
INNER JOIN (SELECT ID, NIC, cast(Row_number()
over (partition by NIC order by ID) as varchar(20)) as RN
FROM FOo) C
on C.ID = B.ID
的第一個結果造成:
ID NIC
567 786-786
897 786-786-1
和SQL Fiddle顯示多個網卡
ID NIC
567 786-786
600 786-786-1
897 786-786-2
10 786-787
12 786-787-1
900 786-787-2
標籤mysql ...你需要什麼數據庫引擎查詢,MS SQL或MySQL? –
它是'MSSQL引擎'。 –