SQL 根据同一列中的其他值更新列
SQL update column depending on other values in same column
我有一个 table 与此类似:
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'
是否有机会在智能更新查询中执行此操作(= 没有游标)?
您可以 运行 update
和 join
得到 row_number()
每行的 [type]
组,然后将这些值与 [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]
假设您的 table 有一个名为 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
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
您可以使用可以更新 cte 的事实:
with cte as(select type, row_number() over(partition by type order by index) rn from table)
update cte set type = type + ' ' + cast(rn as varchar(10))
我有一个 table 与此类似:
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'
是否有机会在智能更新查询中执行此操作(= 没有游标)?
您可以 运行 update
和 join
得到 row_number()
每行的 [type]
组,然后将这些值与 [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]
假设您的 table 有一个名为 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
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
您可以使用可以更新 cte 的事实:
with cte as(select type, row_number() over(partition by type order by index) rn from table)
update cte set type = type + ' ' + cast(rn as varchar(10))