22,199
社区成员
发帖
与我相关
我的任务
分享
select id,max(姓名) as 姓名,max(地址) as 地址,max(邮编) as 邮编
from tableA
group by id
--> 测试数据: [tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb] (ID int,姓名 varchar(4),电话 int,地址 varchar(10))
insert into [tb]
select 1001,'李三',null,null union all
select 1008,'李三',6639405,'东石路'
go
--先修改
update tb set 电话=(select top 1 电话 from tb where ID in (1001, 1008) order by len(电话) desc),
地址=(select top 1 地址 from tb where ID in (1001, 1008) order by len(地址) desc)
from tb a
where ID=1001
--删除多余的
delete tb from tb a where ID=1008
--查看结果:
select * from [tb]
--结果:
ID 姓名 电话 地址
----------- ---- ----------- ----------
1001 李三 6639405 东石路
--> 测试数据: [tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb] (ID int,姓名 varchar(4),电话 int,地址 varchar(10))
insert into [tb]
select 1001,'李三',null,null union all
select 1008,'李三',6639405,'东石路' union all
select 1413,'李三',null,'东石路29号'
go
--先修改
update tb set 电话=(select top 1 电话 from tb where 姓名=a.姓名 order by len(电话) desc),
地址=(select top 1 地址 from tb where 姓名=a.姓名 order by len(地址) desc)
from tb a
where not exists(select 1 from tb where 姓名=a.姓名 and id<a.id)
--删除多余的
delete tb from tb a where exists(select 1 from tb where 姓名=a.姓名 and id<a.id)
--查看结果:
select * from [tb]
-结果:
ID 姓名 电话 地址
----------- ---- ----------- ----------
1001 李三 6639405 东石路29号
select
distinct
姓名,
电话=(select top 1 电话 from tb where 姓名=t.姓名 order by len(isnull(电话,'')) desc),
地址=(select top 1 地址 from tb where 姓名=t.姓名 order by len(isnull(地址,'')) desc)
from tb t