0
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

提前致谢!

4

2 回答 2

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
于 2013-05-21T08:49:34.770 回答
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

于 2013-05-21T10:19:01.557 回答