我有两个看起来像这样的表。
表格申请人
LName FName MI
Adamson Leon R
Alfano Vincent
Bost Darrod D
表ApplicantScore
ID Name Score
1 Adamson, Leon R. 89
2 Alfano, Vincent 99
3 Bost, Darrod D. 81
4 Smith, John 90
5 Chen, Lao 90
...
任何具有MI的名称都以句号结尾。
我需要使用表Applicant中的数据来从表ApplicantScore中检索信息。因此,最终看起来像
ID Name Score
1 Adamson, Leon R 89
2 Alfano, Vincent 99
3 Bost, Darrod D 81
我正在使用此SQL,但没有得到所需的内容。
select a.ID, a.name, a.score
from Applicant a
left join ApplicantScore b
on (REPLACE(b.Name, ' ', '') = REPLACE(a.LName + ',' + a.FName +
ISNULL(a.MI, ''), ' ', ''));
我得到的结果是:
ID Name Score
NULL NULL NULL
2 Alfano, Vincent 99
NULL NULL NULL
请帮助?
答案 0 :(得分:4)
select b.id, b.name, b.score
from Applicant a
inner join ApplicantScore b
on (b.Name = a.LName | ', ' | a.FName |
CASE WHEN a.MI IS NULL THEN ''
ELSE ' ' | a.MI
END));
或按照@scsimon的建议在两端删除空格
select b.id, b.name, b.score
from Applicant a
inner join ApplicantScore b
on (REPLACE(b.Name, ' ', '') =
REPLACE(a.LName | ',' | a.FName | ISNULL(a.MI, ''), ' ', ''));
答案 1 :(得分:1)
根据我的评论中的建议...
declare @Applicant table (LName varchar(64), FName varchar(64), MI char(1))
declare @ApplicantScore table (ID int identity (1,1), [Name] varchar(256), Score int)
insert into @Applicant
values
('Adamson','Leon','R'),
('Alfano','Vincent',null),
('Bost','Darrod','D')
insert into @ApplicantScore
values
('Adamson, Leon R',89),
('Alfano, Vincent',99),
('Bost, Darrod D',81),
('Smith, John',90),
('Chen, Lao',90)
select b.ID, b.name, b.Score
from @Applicant a
INNER JOIN @ApplicantScore b on
replace(b.Name,' ','') = (RTRIM(a.LName) + ',' + RTRIM(a.FName) + ISNULL(a.MI,''))