我有一张包含样本数据的表格如下:
Name | Code
Ken Ken_A
Ken Ken_B
Tim Tim_1
Tim Tim_3
Sam Sam_Tens
Sam Sam_Tenson
我想做一个更新查询,用第一个实例替换Name命令的Code的第二个实例,所以我最终会得到以下内容:
Name | Code
Ken Ken_A
Ken Ken_A
Tim Tim_1
Tim Tim_1
Sam Sam_Tens
Sam Sam_Tens
答案 0 :(得分:3)
假设您有一个指定排序的列,您可以使用带有连接的可更新CTE:
with toupdate as (
select t.*, row_number() over (partition by name order by id) as seqnum
from t
)
update toupdate
set code = tu2.code
from toupdate join
toupdate tu2
on toupdate.name = tu2.name and
tu2.seqnum = 1 and
toupdate.seqnum > 1;
如果您没有标识行排序的列,那么您的问题没有意义。在SQL中,表本质上是无序的。
答案 1 :(得分:1)
一个选项:
update mytable
set code = (select min(code) from mytable min_name where min_name.name = mytable.name);
答案 2 :(得分:1)
您可以使用此查询使用相关的子查询:
UPDATE t1 SET Code = (SELECT TOP 1 t2.Code FROM dbo.TableName t2
WHERE t1.Name = t2.Name
ORDER BY Name, Code)
FROM dbo.TableName t1
WHERE (SELECT COUNT(*) FROM dbo.TableName t2
WHERE t1.Name = t2.Name) > 1