删除重复记录并设置主键
现在表中存在多条重复记录
A         B          C         D
---   ----    ----    ----
A123    123456      北京        天天
A123    123456      北京        天天
A123    123456      北京        天天
A124    123457      北京         
A124    123457      北京               
A125    123458      上海        圆圆
A125    123458      上海
现在就是要删除重复记录(A,B,C字段重复),如果D不为空的话,则优先保存D不为空的记录
结果如下:
A         B          C         D
---   ----    ----    ----
A123    123456      北京        天天      
A124    123457      北京               
A125    123458      上海        圆圆
------解决方案--------------------http://topic.csdn.net/u/20071022/09/ffd47c85-2faf-484c-b573-e2c719c108a0.html
我这里写得比较详细
------解决方案--------------------/*------------------------
/*现在表中存在多条重复记录  
A         B          C         D  
---   ----    ----    ----  
A123    123456      北京        天天  
A123    123456      北京        天天  
A123    123456      北京        天天  
A124    123457      北京        
A124    123457      北京              
A125    123458      上海        圆圆  
A125    123458      上海  
现在就是要删除重复记录(A,B,C字段重复),如果D不为空的话,则优先保存D不为空的记录  
结果如下:  
A         B          C         D  
---   ----    ----    ----  
A123    123456      北京        天天     
A124    123457      北京              
A125    123458      上海        圆圆 */
go
create table tb(A nvarchar(8), B nvarchar(8), C nvarchar(16), D nvarchar(16))
insert tb select 'A123', '123456', '北京', '天天'  
union all select 'A123', '123456', '北京', '天天'  
union all select 'A123', '123456', '北京', '天天'  
union all select 'A124', '123457', '北京', null        
union all select 'A124', '123457', '北京', null                
union all select 'A125', '123458', '上海', '圆圆'  
union all select 'A125', '123458', '上海', null 
--select * from tb
select A,B,C,max(D) as D into #T from tb group by A,B,C
truncate table tb
insert tb select * from #T
select * from tb
drop table #T
drop table tb
------------------------*/
(7 row(s) affected)
Warning: Null value is eliminated by an aggregate or other SET operation.
(3 row(s) affected)
(3 row(s) affected)
A        B        C                D
-------- -------- ---------------- ----------------
A123     123456   北京               天天
A124     123457   北京               NULL
A125     123458   上海               圆圆
(3 row(s) affected)
------解决方案--------------------SQL code
go
create table tb(A nvarchar(8), B nvarchar(8), C nvarchar(16), D nvarchar(16))
insert tb select 'A123', '123456', '北京', '天天' 
union all select 'A123', '123456', '北京', '天天' 
union all select 'A123', '123456', '北京', '天天' 
union all select 'A124', '123457', '北京', null         
union all select 'A124', '123457', '北京', null                 
union all select 'A125', '123458', '上海', '圆圆' 
union all select 'A125', '123458', '上海', null  
--select * from tb
select A,B,C,max(D) as D into #T from tb group by A,B,C
truncate table tb
insert tb select * from #T
select * from tb
drop table #T
drop table tb