首页 > 解决方案 > 检查两个字符串中相同位置的字符是否相等

问题描述

我有一张如下表

在此处输入图像描述

如果同一位置的任何字符相等,我想得到表格的结果

例子:

名:ANURADHA KONGARI
姓名AK

无首字母AI

在此示例中,AK 的首字母和 AI 的首字母相等。所以它应该返回结果。

我尝试过使用substring,但它会导致所有记录。因为长度

我尝试过的例子

select fullname, names, withoutinitials from #localtable where substring(names,1,1)= substring(withoutinitials,1,1)
or
substring(names,2,1)= substring(withoutinitials,2,1)
or
substring(names,3,1)= substring(withoutinitials,3,1)

这是我尝试过的一种方法。它正在工作,但是如果字符串长度大于 4 怎么办

create table #lt2(fullname varchar(100))
insert into #lt2 select getName=case  
    when len(names)=1 and substring(names,1,1) = substring(withoutinitials,1,1) 
    then fullname 
    when len(names)=2 and ((substring(names,1,1) = substring(withoutinitials,1,1))or(substring(names,2,1) = substring(withoutinitials,2,1))) 
    then fullname 
    when len(names)=3 and ((substring(names,1,1) = substring(withoutinitials,1,1))or(substring(names,2,1) = substring(withoutinitials,2,1)) or (substring(names,2,1) = substring(withoutinitials,2,1))) 
    then fullname 
    when len(names)=4 and ((substring(names,1,1) = substring(withoutinitials,1,1))or(substring(names,2,1) = substring(withoutinitials,2,1)) or (substring(names,2,1) = substring(withoutinitials,2,1))
    or (substring(names,3,1) = substring(withoutinitials,3,1))) 
    then fullname else ''
    end
    from #localtable

select * from #lt2 where fullname!=''

但这会导致所有记录,因为某些记录的长度可能不是 3,所以它甚至返回长度为 1 的名称。

如果两个字符串的至少一个字符在同一位置相等,我想得到结果。

比如字符串 1 的第 1 个位置 = 字符串 2 的第 1 个位置或 string1 的第 2 个位置 = 字符串 2 的第 2 个位置。

谢谢你。

标签: sqlsql-server

解决方案


'0'与fornames'1'for具有不相等字符的右填充withoutinitials

select fullname, names, withoutinitials from #localtable where 
substring(names, 1, 1) = substring(withoutinitials, 1, 1)
or
substring(LEFT(CONCAT(names, '0'), 2), 2, 1) = substring(LEFT(CONCAT(withoutinitials, '1'), 2), 2, 1)
or
substring(LEFT(CONCAT(names, '00'), 3), 3, 1) = substring(LEFT(CONCAT(withoutinitials, '11'), 3), 3, 1)
or
substring(LEFT(CONCAT(names, '000'), 4), 4, 1) = substring(LEFT(CONCAT(withoutinitials, '111'), 4), 4, 1)


带有样本数据:

INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc1', 'GR', 'AM');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc2', 'G', 'A');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc3', 'GR', 'GM');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc4', 'R', 'R');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc5', 'GRAA', 'AMAM');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc6', 'GRS', 'AMS');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc7', 'AGR', 'AAM');
INSERT INTO localtable (fullname, names, withoutinitials) VALUES ('abc8', 'GR', 'AM');

结果是:

    fullname    names   withoutinitials
1   abc3        GR      GM
2   abc4        R       R
3   abc5        GRAA    AMAM
4   abc6        GRS     AMS
5   abc7        AGR     AAM

推荐阅读