简体   繁体   English

根据逗号分隔列中的所有(多个)值列表选择行,使用 % 前后进行模糊匹配

[英]Selecting rows based on a list of ALL (multiple) values in a comma delimited column using % before and after for fuzzy match

Editing as requested.按要求编辑。 I was able to get the data from a long string into a table so the question has changed to a degree.我能够将长字符串中的数据放入表格中,因此问题在一定程度上发生了变化。

My question is how do I get results returned based on a match of ALL values passed via a comma-delimited string?我的问题是如何根据通过逗号分隔的字符串传递的所有值的匹配项返回结果?

I can, and have, used STRING_SPLIT .我可以并且已经使用过STRING_SPLIT The problem I have is when using string split with IN or INNER JOIN or OUTER APPLY or CROSS APPLY , a row is returned if any one (01)value in the passed string of values matches the value(s) in the column of the row;我遇到的问题是,当将字符串拆分与ININNER JOINOUTER APPLYCROSS APPLY一起使用时,如果传递的值字符串中的任何一个 (01) 值与行列中的值匹配,则返回一行; NOT ALL of the values in the string.不是字符串中的所有值。

Again, the important point is that the rows returned need to match ON ALL values from the STRING_SPLIT of the values passed in the character string.同样,重要的一点是返回的行需要匹配字符串中传递的值的STRING_SPLIT中的所有值。

Also, as previously requested, here is a table example, a mocked-up piece of code and the expected results:此外,按照之前的要求,这里有一个表格示例、一段代码模型和预期结果:

Code:代码:

DECLARE @VALUES NVARCHAR(100) = 'X,G'

SELECT T5.COL1, T5.COL2, STRING_AGG(TRIM(TABLE1.COL3),', ') AS UNIQUE_STRING_OF_VALUES
FROM [SOME_DB].[dbo].[TABLE1] AS T5 
INNER JOIN STRING_SPLIT(@VALUES, ',') AS T10 ON T10.VALUE = T5.COL3

GROUP BY T5.COL1, T5.COL2
ORDER BY T5.COL1 ASC, T5.COL2 ASC

在此处输入图像描述

You can achieve this by using a built-in function that splits the strings:您可以通过使用拆分字符串的内置 function 来实现此目的:

declare
    @String             varchar(1000)   =   'This,is,a,test,search,function'
,   @SplitCharacter     varchar(10)     =   ','

select
*
from    string_split(@String,@SplitCharacter)

This splits the strings in this format:这将以这种格式拆分字符串:

结果1

Now when you alter the script like this, you can search for particular fields in the splits:现在,当您像这样更改脚本时,您可以在拆分中搜索特定字段:

declare
    @String             varchar(1000)   =   'This,is,a,test,search,function'
,   @SplitCharacter     varchar(10)     =   ','

select
*
from    string_split(@String,@SplitCharacter)
where   Value like '%sea%'

This gives you the following results:这将为您提供以下结果:

结果2

See DEMO演示

Let me know if this works...让我知道这个是否奏效...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM