如果所有其他列始终为空,您可以像这样使用此视图并获得良好的性能:
CREATE VIEW v_yourview as
SELECT id, row, min(customer) over (partition by id) customer,
min(project) over (partition by id) project,
min(plant) over (partition by id) plant,
sheetname
from myInputTable
如果要更新所有行。由于您的数据中没有时间戳或唯一 ID,我通过添加临时 row_number 来伪造它:(我相信您在小提琴中犯了错误,我试图纠正它)
CREATE TABLE #myInputTable
(
id int,
row int,
customer varchar(30),
project varchar(30),
plant varchar(30),
sheetname varchar(30),
comment varchar(30)
);
INSERT INTO #myInputTable
(id, row, customer,project,plant, sheetname,comment)
VALUES
(1,1, 'Customer Name', 'Project Name', 'Plant Name', 'sheet 1','comment 1')
,
(1,1,NULL ,NULL ,NULL , 'sheet 2',Null)
,(1,1,NULL ,NULL ,NULL , 'sheet 3',Null)
,(1,2,NULL ,NULL ,NULL , 'sheet 2','comment 2')
,(1,2,NULL ,NULL ,NULL , 'sheet 3',Null)
-- I changed value for ID from 1 to 2 in next line
,(2,1, 'Customer Name 2', 'Project Name', 'Plant Name', 'sheet 1', 'new comment')
,
(2,1,NULL ,NULL ,NULL , 'sheet 2',Null)
,(2,1,NULL ,NULL ,NULL , 'sheet 3',Null)
,(2,2,NULL ,NULL ,NULL , 'sheet 2',Null)
,(2,2,NULL ,NULL ,NULL , 'sheet 3',Null)
;with t1 as
(
select *, row_number() over (order by id) rn
from #myInputTable
)
update t1
set
customer = t2.customer,
project = t2.project,
plant = t2.plant,
comment = t3.comment
from t1
join #myInputTable t2
on t2.customer is not null
and t1.id = t2.id
cross apply(select top 1 comment from t1 t where rn <= t1.rn and comment is not null order by rn desc) t3
where t1.customer is null
select * from #myInputTable