将表格连接到自身,没有特定的ID
我有一个没有ID列的客户记录表,客户可能会多次出现在表中,并填充了各种列。我已设法构建一个完全弹出但不是客户唯一的INIT_SURNAME列。如何合并行以匹配具有相同INIT_SURNAME并共享另一个公共数据元素的客户。例如,我想从下表返回3个cutomers,前3行是同一个人。
e.g
INPUT:
INIT_SURNAME|EMAIL|PHONE|OTHERID
J*SOAP|js@x.com|4321|
J*SOAP|js@x.com||
J*SOAP||4321|4
J*SOAP|otherjoe@y.com||2
J*DOE||12345|3
输出:
INIT_SURNAME|EMAIL|PHONE|OTHERID
J*SOAP|js@x.com|4321|4
J*SOAP|otherjoe@y.com||2
J*DOE||12345|3
可以这样做吗?
答案 0 :(得分:1)
您可以单独合并每列。
T-Sql中的示例代码:
declare @foo table (
name varchar(30),
email varchar(30),
phone varchar(30),
id varchar(30)
)
insert into @foo values
('J*SOAP','js@x.com','4321',NULL),
('J*SOAP','js@x.com',NULL,NULL),
('J*SOAP',NULL,'4321','4'),
('J*SOAP','otherjoe@y.com',NULL,'2'),
('J*DOE',NULL,'12345','3')
;with
merge_by_email as (
select name, email, MAX(phone) as phone, MAX(id) as id
from @foo
group by name, email
),
merge_by_phone as (
select name, max(email) as email, phone, MAX(id) as id
from merge_by_email
group by name, phone
),
merge_by_id as (
select name, max(email) as email, MAX(phone) as phone, id
from merge_by_phone
group by name, id
)
select * from merge_by_id