sql - 选择在一个字符串列中从另一个字符串中出现最少的记录
问题描述
我在处理从名称字符串参数中选择名称列中至少出现 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 并结合一个函数来计算字符串出现次数,但我不能一直得到它。
希望有人在这里有一些好主意。
提前致谢。
解决方案
您可以拆分您正在搜索的名称列以及 @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
推荐阅读
- qt - Qt Widgets 针对多种平台和语言进行缩放
- javascript - java - 如何使用spring boot将回调方法从JavaScript传递到java后端?
- mysql - 如何在我的 django 应用程序中创建 model.py 以实现我的需要?
- mysql - 无法在mysql中创建表
- c# - 如何在 C# 中为自动获取更新事件的 ics 类型文件创建链接
- python - 屏幕关闭时 Python 脚本停止运行
- rxjs - RXJS:自适应超时
- android - 屏幕旋转后,无法从 AsyncTask 以编程方式关闭 BottomSheetDialogFragment
- android - Firebase Deep Link 打开的是 Play 商店而不是 App
- django - 在 amazon s3 中压缩字体文件