2014-07-24 57 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