在SQL Server中使用like运算符查找名称

时间:2017-03-30 09:01:45

标签: sql-server

我有表格列

surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard

forename应该相同且姓氏部分相同(意味着空格之前的字符串应该相同,空格不应该相同)

输出如

surname    forename
Dane jr    Carlo
Dane Br    Carlo

5 个答案:

答案 0 :(得分:2)

select 
c.* from table c
join
(select substring(surname,1,charindex(' ',surname,1)) as namee,forename from table
group by
substring(surname,1,charindex(' ',surname,1)),forename
having count(*)>1
) b
on c.surname like '%'+b.namee+'%'
and c.forename=b.forename

另一种方法:

;with cte
as
(
select *,count(*) over (partition by substring(surname,1,charindex(' ',surname,1)),forename ) as cnt
from table
)
select * from cte  where cnt>1

答案 1 :(得分:1)

这应该有效,请用更大的数据集进行测试。它将返回名称不止一次出现的任何行。它根据forename和姓氏的第一部分(在空格之前,如果存在的话)匹配行。

CREATE TABLE #names
    (
      surname NVARCHAR(50) ,
      forename NVARCHAR(50)
    );

INSERT  INTO #names
        ( surname, forename )
VALUES  ( 'Dane jr', 'Carlo' ),
        ( 'Dane Br', 'Carlo' ),
        ( 'Daniel', 'Gerard' );

SELECT  surname ,
        n1.forename
FROM    #names n1
        INNER JOIN ( SELECT LEFT(surname, CHARINDEX(' ', surname)) FirstPartSurname ,
                            forename
                     FROM   #names
                   ) n2 ON n2.forename = n1.forename
                           AND n1.surname LIKE n2.FirstPartSurname + '%'
GROUP BY n1.surname ,
        n1.forename
HAVING  COUNT(1) > 1;


DROP TABLE #names;

产地:

surname  forename
Dane Br  Carlo
Dane jr  Carlo

答案 2 :(得分:0)

另一种选择:

Declare @tbl table(surname varchar(30),forename varchar(30))
insert into @tbl(surname,forename)values
('Dane jr','Carlo'),
('Dane Br','Carlo'),
('Daniel','Gerard')

select a.surname,forename from
(select sdx,rcount,surname,forename from
(select soundex(surname) as sdx,row_number() over(partition by soundex(surname) order by soundex(surname)) as rcount, surname,forename from @tbl) as a
) as a
right join

(select sdx,rcount,surname from
(select soundex(surname) as sdx,row_number() over(partition by soundex(surname) order by soundex(surname)) as rcount, surname from @tbl) as a
where rcount >1)  as b
on a.sdx = b.sdx

输出:

Dane jr Carlo
Dane Br Carlo

答案 3 :(得分:0)

WITH CTE (namee, forename) AS (
select  LEFT(surname,charindex(' ',surname,1)) as namee, forename
from tabTestName
group by forename, LEFT(surname,charindex(' ',surname,1)) having count(*)>1 
) select t.* from CTE join tabTestName t

on t.surname喜欢'%' + CTE.namee +'%' 和t.forename = CTE.forename

答案 4 :(得分:0)

我已为此

添加了id列

Dane Br Carlo 2 Daniel Gerard 3 Moore Jr A 4 Moore Jr A 5我需要这个作为out put surname forename id Dane jr Carlo 1 Dane Br Carlo 2但是输出显示了姓氏名字 Dane jr Carlo 1 Dane Br Carlo 2 Moore Jr A 4 Moore Jr A 5