2014-02-13 34 views
0

我希望我能很好地解释我的问题。
我有一个没有主键的表。为了得到唯一的行,我必须select distinct (make, model, category,onhand)在一起,结果是2行的每一个与现有量is null和其他现有量is not null
sql server更新同一表中的重复行

现在我要做的就是更新我的表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 

但我无法弄清楚如何更新手动null。我正在使用SQL Server 2008 R2。
谢谢

回答

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; 
+0

日Thnx很多,第二个就是我到底需要! – Sam