sql server更新同一个表中的重复行

时间:2014-02-13 18:05:58

标签: sql sql-server

我希望我能很好地解释我的问题 我有一张没有主键的表。要获得唯一的行,我必须select distinct (make, model, category,onhand)一起,结果是每行2行,其中is null和另一行is not null

现在我要做的是将每个重复行的表更新为set null onhand = onhand with value 我有这个查询来查找每个

的重复项-2
select  distinct MAKE, MODEL, category, PRGR,
CountDuplicateRows= COUNT(1)    --column to count the number of duplicates
from [OITM2]
WHERE PRGR !='p'
GROUP BY  MAKE, MODEL, category, PRGR
HAVING COUNT(1)>1   --more than one record
ORDER BY COUNT(1) DESC  --sort by most duplicates

但我无法弄清楚如何更新on null。我正在使用sql server 2008 r2。
谢谢

1 个答案:

答案 0 :(得分:2)

SQL Server具有可更新的CTE和子查询的非常好的功能。你可以这样做:

with toupdate as (
      select t.*,
             count(*) over (partition by  MAKE, MODEL, category, PRGR) as cnt
      from oitm2
      where prgr <> 'p'
     )
update toupdate
    set onhand = YOURVALUEGOESHERE
    where cnt > 1 and onhand is null;

请注意,子查询不使用聚合,而是使用count()窗口函数。这会将计数附加到原始数据的每一行 - 它仍可用于更新。

如果您想从同一组行中获取任意值,可以将其添加到toupdate

with toupdate as (
      select t.*,
             count(*) over (partition by  MAKE, MODEL, category, PRGR) as cnt,
             max(onhand) over (partition by  MAKE, MODEL, category, PRGR) as onhand_value
      from oitm2
      where prgr <> 'p'
     )
update toupdate
    set onhand = onhand_value
    where cnt > 1 and onhand is null;