如何更新site_id
除最后一行之外的所有重复行。即,如果我有 3 个重复的站点 id(在这种情况下为 2 个),我如何更新前两个而使最后一个(第三个)保持不变?
temp_id site_id amount
1 2 200
2 2 200
3 2 200
4 3 200
5 3 200
6 4 200
创建表#site(temp_id NUMERIC IDENTITY,site_id NUMERIC PRIMARY KEY)
INSERT INTO #site VALUES(2),(3),(4)
CREATE TABLE #temp (temp_id NUMERIC IDENTITY,
site_id NUMERIC FOREIGN KEY (site_id) REFERENCES #site(site_id),
amount NUMERIC)
INSERT INTO #temp VALUES(2,200),(2,200),(2,200),(3,200),(3,200),(4,200)
update #temp
set amount = 2
where site_id in (
select distinct table1.site_id
from #temp table1
inner join #temp table2 on table1.site_id = table2.site_id
and table1.temp_id <> table2.temp_id
)
and site_id <> (
select max(site_id)
from #temp
);
SELECT t.* FROM #temp t
JOIN #site s ON s.site_id = t.site_id
DROP TABLE #temp
DROP TABLE #site