MyField Description
------- -----------
A001 Alcantara
A002 Apacible
Arctic
Arkansas
B001 Backdoor
Ballpen
Brother
..and so on
在上面的记录中,如何在T-SQL中查询(在一个查询中)以更新具有如下输出:
MyField Description
------- -----------
A001 Alcantara
A002 Apacible
A003 Arctic
A004 Arkansas
B001 Backdoor
B002 Ballpen
B003 Brother
提前致谢!
答案 0 :(得分:1)
试试这个:
;WITH CTE as
(
select myfield,description,ROW_NUMBER() over (partition by left([Description],1) order by [Description]) as rn
from Table1
)
UPDATE CTE
SET Myfield=left(description,1) +CASE WHEN rn <= 9 then '00' else '0' end+cast(rn as varchar(3)) from CTE
答案 1 :(得分:0)
也可以通过子查询完成。只是另一种方式。
UPDATE Table1 SET MyField = SortByDesc.ID
FROM
Table1 AS Original
INNER JOIN (SELECT Description,
LEFT(Description,1)+
RIGHT(REPLICATE('0', 3) + CAST((ROW_NUMBER() OVER (PARTITION BY LEFT(Description, 1) ORDER BY [Description])) AS NVARCHAR), 3) AS ID
FROM Table1) AS SortByDesc ON Original.Description = SortByDesc.Description
我在SQL Fiddle上尝试过:http://sqlfiddle.com/#!3/db079/26/0