2014-07-24 58 views
0
id name number counter 
1 test 010101 2 
2 test 010101 1 

我需要选择具有相同数字名称组合的重复行。我需要更新计数器在两行中的计数器的总和之一,然后删除第二行在SQL Server中将重复行合并为一行

我正在使用下面的查询来选择重复,但我无法做更新:

SELECT * 
FROM [prof] 
WHERE ID NOT IN 
    (
    SELECT MAX(ID) 
    FROM [prof] 
    GROUP BY number, name 
) 
+0

这是否有关系你保留哪些编号? – SQLChao

回答

0

更新会是这样的。

update prof 
set counter = counterSum 
from prof join 
(select name, number, sum(counter) counterSum 
from prof 
where whatever 
group by name, number) temp on prof.name = temp.name and prf.number = temp.number 
where whatever 

两个“哪里都应该是相同的。

1

这将需要两个语句,最好裹在一个交易:

update prof 
set counter = (select SUM(counter) from prof group by number, name) 
where ID in (select MAX(id) from prof group by number, name); 

delete from prof where ID not in 
(select MAX(id) from prof group by number, name); 
1

这将更新计数器,并保持第一(最低)的标识。它将只保留一个唯一的ID,所以如果有3个或更多的行具有相同的名称,这个数字仍然可以工作。

Update [prof] 
set counter=a.cnt 
from [prof] p inner join ( 
    select name,number,sum(counter)cnt 
    from [prof] 
    group by name,number)a 
on p.name=a.name and p.number=a.number; 

delete [prof] 
from [prof] join (
    select id,row_number() over (partition by name, number order by id asc)row 
    from [prof])d 
on [prof].id=d.id 
where d.row>1; 
1

这是一种使用cte的方法。这里是cte看起来像什么

id name number counter totalCounter DupNum 
2 test1 10101   1   3   1 
1 test1 10101   2   3   2 
5 test2 10102   5   12   1 
4 test2 10102   4   12   2 
3 test2 10102   3   12   3 

你可以用注释掉的delete语句来运行整个事情来更新数据。然后注释掉更新语句并取消注销并重新运行。

;WITH table1_cte 
AS 
(
    SELECT id 
    name, 
    number, 
    counter, 
    ROW_NUMBER() over(PARTITION BY name, number ORDER BY id DESC) AS DupNum, 
    SUM(counter) over (PARTITION BY name, number) AS totalCounter 
    FROM prof 
) 

UPDATE table1_cte 
SET counter = totalCounter 
WHERE dupnum =1 

--DELETE FROM table1_cte 
--WHERE dupnum > 1