2010-08-02 93 views
1

我有表中有第15列我想合并重复行在一行,然后删除该重复行后保留一行作为记录如何合并重复行然后删除所有重复后保持行

我的表像

id name email address city state country salary .... 
1 a [email protected] null null a  xyx null 
2 null [email protected] a  a  null null 10000 
+1

检查这个线程http://stackoverflow.com/questions/1748459/deleting-duplicate-record-from-table-sql-query/1748770# 1748770 – 2010-08-02 07:36:29

回答

1

你可以小组email和更新与GroupWise的最大所有列:

declare @t table (id int, name varchar(50), email varchar(50), 
    address varchar(50), city varchar(50), state varchar(50), 
    country varchar(50), salary int) 
insert @t 
values (1, 'a', '[email protected]', null, null, 'a', 'xyx', null), 
     (2, null, '[email protected]', 'a', 'a', null, null, 10000) 

-- Update all rows for an email address 
update t 
set  name = combined.name 
,  address = combined.address 
,  city = combined.city 
,  state = combined.state 
,  country = combined.country 
,  salary = combined.salary 
from @t t 
join (
     select 
       max(name) as name 
     ,  email 
     ,  max(address) as address 
     ,  max(city) as city 
     ,  max(state) as state 
     ,  max(country) as country 
     ,  max(salary) as salary 
     from @t 
     group by 
       email 
     ) combined 
on  combined.email = t.email 

然后删除所有杜褶行:

-- Delete duplicate rows 
delete t 
from @t t 
join @t t2 
on  t2.email = t.email 
     and t2.id < t.id 

-- Display result 
select * from @t 

此打印:

id name email address city state country salary 
1 a [email protected] a  a a  xyx  10000