如何为列中的唯一字符串分配数字?

时间:2017-01-10 15:39:42

标签: sql sql-server sql-server-2008

我的意思是...... 我们假设您在

下有以下单元格值
column1
1. Sedan
2. Trucks
3. SUV
4. SportsCar

我想要做的是创建一个向Sedan,Trucks,SUV等插入值1的查询。(仅举几个单元格值作为示例,我需要为数百行执行此操作。)

看起来像这样:

1. Sedan1
2. Trucks2
3. SUV3
4. SportsCar4

这甚至可能吗?

3 个答案:

答案 0 :(得分:0)

SQL服务器

with Products as
(
select product, row_number() over(order by a_column) as R_ord
from mytable
)
update Products 
set product = product + cast(R_ord as varchar(50))

另外,为什么?为什么不用表来做呢?

答案 1 :(得分:0)

CREATE TABLE #b
    ([column1] varchar(9))
;

INSERT INTO #b
    ([column1])
VALUES
    ('Sedan'),
    ('Trucks'),
    ('SUV'),
    ('SportsCar')
;

with Products as
(
select [column1], row_number() over(order by [column1]) as upd
from #b
)

select  [column1] =  [column1] + cast(upd as varchar(50)) from products

输出

column1
Sedan1
SportsCar2
SUV3
Trucks4

答案 2 :(得分:0)

一种方法是将值与row_number函数上的强制转换连接起来。但如前所述,不确定为什么要这样做。

select top 10 
column1 + cast(row_number() over (order by column1 ) as varchar(10)) 
from my table