SQL更新列取决于同一列

时间:2015-05-05 15:59:23

标签: sql sql-server sql-server-2014

我有一张类似的表:

Index    Name       Type
--------------------------------
1        'Apple'   'Fruit'
2        'Carrot'  'Vegetable'
3        'Orange'  'Fruit'
3        'Mango'   'Fruit'
4        'Potato'  'Vegetable'

并希望将其更改为:

Index    Name       Type
--------------------------------
1        'Apple'   'Fruit 1'
2        'Carrot'  'Vegetable 1'
3        'Orange'  'Fruit 2'
3        'Mango'   'Fruit 3'
4        'Potato'  'Vegetable 2'

是否有机会在智能更新查询中执行此操作( =没有游标)?

4 个答案:

答案 0 :(得分:3)

您可以使用update运行join以获取每行[type]组中的row_number(),然后使用[type]将此值与[index]连接起来}作为胶柱:

update t1 set t1.[type] = t1.[type] + ' ' + cast(t2.[rn] as varchar(3))
from [tbl] t1
join ( select [index]
            , row_number() over (partition by [type] order by [index]) as [rn]
       from [tbl]
     ) t2 on t1.[index] = t2.[index]

SQLFiddle

答案 1 :(得分:0)

假设您的表有一个名为ID的主键,那么您可以运行以下命令:

update fruits
set Type = newType
from
(
select f.id
       ,f.[index] 
       ,f.Name 
       ,f.[Type] 
       ,Type + ' '+ cast((select COUNT(*) 
                          from fruits 
                          where Type = f.Type 
                          and Fruits.id <= f.id) as varchar(10)) as newType
    from fruits f
) t
where t.id = fruits.id

答案 2 :(得分:0)

SELECT Index ,Name, Type, ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Index)AS RowNum
INTO #temp
FROM table_name

UPDATE #temp
SET Type = Type + ' ' + CAST(RowNum AS NVARCHAR(15))

UPDATE table_name
SET Type = t2.Type
FROM table_name t1
JOIN #temp t2 ON t2.Index = t1.Index

答案 3 :(得分:0)

您可以使用以下事实:您可以更新cte:

false