首页 > 解决方案 > 选择在一个字符串列中从另一个字符串中出现最少的记录

问题描述

我在处理从名称字符串参数中选择名称列中至少出现 2 次的人员记录时遇到了挑战。

create table #persons (id int not null, [name] nvarchar(200) not null  )

insert into #persons VALUES (1, 'Paul Nelson')
insert into #persons VALUES (2, 'Paul Eric Smith')
insert into #persons VALUES (3, 'Paul Parsons Cline')
insert into #persons VALUES (4, 'Greg Olav Smith')
insert into #persons VALUES (5, 'Paul Henry Gregory Hansson')
insert into #persons VALUES (6, 'Parsons Henry Smith')

declare @name_to_search_for nvarchar(200) = 'Paul Smith Parsons'

我想要的是从#persons 中选择具有两次或多次出现的名称部分的ID @name_to_search_for

在上面的示例中,我想获取结果集

2
3
6

我尝试过的是用来STRING_SPLIT(@name_to_search_for, ' ')获得一个结果集,我可以交叉加入 #persons 并结合一个函数来计算字符串出现次数,但我不能一直得到它。

希望有人在这里有一些好主意。

提前致谢。

标签: sqlsql-servertsql

解决方案


您可以拆分您正在搜索的名称列以及 @name_to_search_for 并加入拆分值。

然后通过 [id]、[name] 获取计数并应用 HAVING COUNT(*) >= 2

像这样,我只是将您的示例更改为表变量:

DECLARE @persons TABLE
    (
        [id] INT NOT NULL
      , [name] NVARCHAR(200) NOT NULL
    );

INSERT INTO @persons
VALUES ( 1, 'Paul Nelson' )
     , ( 2, 'Paul Eric Smith' )
     , ( 3, 'Paul Parsons Cline' )
     , ( 4, 'Greg Olav Smith' )
     , ( 5, 'Paul Henry Gregory Hansson' )
     , ( 6, 'Parsons Henry Smith' );

DECLARE @name_to_search_for NVARCHAR(200) = N'Paul Smith Parsons';


SELECT      [per].[id]
          , [per].[name]
FROM        @persons [per]
CROSS APPLY [STRING_SPLIT]([per].[name], ' ') [perp] --Split the name column you are seaching
INNER JOIN  [STRING_SPLIT](@name_to_search_for, ' ') [srch]
    ON [srch].[value] = [perp].[value] --Split @name_to_search for and join that to the split name column
GROUP BY    [per].[id]
          , [per].[name]
HAVING      COUNT(*) >= 2; --Group and only return those with 2 or more

给你结果:

id          name                  
----------- -----------------------
2           Paul Eric Smith     
3           Paul Parsons Cline   
6           Parsons Henry Smith 

推荐阅读