如何合并重复行,然后在保留行后删除所有重复项

时间:2010-08-02 07:31:14

标签: asp.net sql

我有Table,因为有第15列我希望在一行中合并重复行,然后在将一行保留为记录后删除该重复行

我的表那样

id name email address city state country salary ....
1   a    a@a.a null   null  a     xyx    null
2   null a@a.a a      a     null  null   10000

1 个答案:

答案 0 :(得分:1)

您可以对email进行分组,并使用groupwise maximum更新所有列:

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', 'a@a.a', null, null, 'a', 'xyx', null),
        (2, null, 'a@a.a', '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    a@a.a a       a    a     xyx     10000