site_id
最後の行を除くすべての重複行を更新するにはどうすればよいですか。つまり、重複したサイトIDが3つ(この場合は2つ)ある場合、最後の(3番目の)1つをそのままにして、上位2つを更新するにはどうすればよいですか?
temp_id site_id amount
1 2 200
2 2 200
3 2 200
4 3 200
5 3 200
6 4 200
CREATE TABLE #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