1

如何更新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
4

2 回答 2

2
UPDATE temp_record
    SET …
    WHERE site_id = 2
        AND temp_id <> (SELECT MAX(temp_id)
                            FROM my_table
                            WHERE site_id = 2)

如果您想更新所有这些行并且temp_id是 中的唯一键temp_record

UPDATE temp_record
    SET …
    WHERE temp_id NOT IN (
        SELECT MAX(temp_id)
            FROM temp_record
            GROUP BY site_id)
于 2012-12-30T22:34:09.767 回答
2

我首选的方法是row_number()

with toupdate as (
     select t.*,
            row_number() over (partition by site_id order by temp_id desc) as seqnum
     from t
)
update t
    set . . .
    where seqnum = 1

我不填写详细信息。只是给你另一种方法。

于 2012-12-31T00:24:51.270 回答