我正在修改一些SQL,使其能够在特定列中存在多个具有相同值的行时更改列的值。
例如:
id col1 col2
1 114 name1
2 114 name2
3 115 name3
在上面我希望能够在第一行和第二行中重命名col2的值,因为col1的值匹配,所以输出实际上是:
id col1 col2
1 114 renamed
2 114 renamed
3 115 name3
有没有办法在SQL Server中执行此操作?
答案 0 :(得分:2)
update tablename
set col2 = 'renamed'
where col1 IN (select col1 from tablename
group by col1
having count(*) > 1)
答案 1 :(得分:0)
是。使用窗口功能非常简单。如果您想将此作为更新:
with toupdate as (
select t.*,
min(col2) over (partition by col1) as mincol2,
max(col2) over (partition by col1) as maxcol2
from t
)
update toupdate
set col2 = 'renamed'
where mincol2 <> maxcol2;