根据重复值更新3行中的2行

时间:2012-12-30 22:29:10

标签: sql tsql

如何更新除最后一行之外的所有重复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

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

2 个答案:

答案 0 :(得分:2)

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

如果您要更新所有此类行,而temp_idtemp_record中的唯一键:

UPDATE temp_record
    SET …
    WHERE temp_id NOT IN (
        SELECT MAX(temp_id)
            FROM temp_record
            GROUP BY site_id)

答案 1 :(得分: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

我没有填写细节。只是给你一个替代方法。