简体   繁体   English

如何在查询中使用分隔字符串作为数组进行搜索

[英]How to search using a delimited string as array in query

I am trying to search for records columns that match a value within a delimited string.我正在尝试搜索与分隔字符串中的值匹配的记录列。

I have two tables that look like this我有两张看起来像这样的桌子

Vehicles车辆

| Id | Make | Model |
|----|------|-------|
| 1  | Ford | Focus |
| 2  | Ford | GT    |
| 3  | Ford | Kuga  |
| 4  | Audi | R8    |

Monitor监视器

| Id | Makes | Models   |
|----|-------|----------|
| 1  | Ford  | GT,Focus |
| 2  | Audi  | R8       |

What I'm trying to achieve is the following:我想要达到的目标如下:

| Id | Makes | Models   | Matched_Count |
|----|-------|----------|---------------|
| 2  | Audi  | R8       | 1             |
| 1  | Ford  | GT,Focus | 2             |

Using the following query I can get matches on singular strings, but I'm not sure how I can split the commas to search for individual models.使用以下查询,我可以获得单数字符串的匹配项,但我不确定如何拆分逗号以搜索单个模型。

select Id, Makes, Models, (select count(id) from Vehicles va where UPPER(sa.Makes) = UPPER(va.Make) AND UPPER(sa.Models) = UPPER(va.Model)) as Matched_Count
from Monitor sa

(I am using a very SQL Server 2016 however I do not have access to create custom functions or variables) (我使用的是非常 SQL Server 2016 但是我无权创建自定义函数或变量)

If you are stuck with this data model, you can use string_split() :如果你被这个数据 model 卡住了,你可以使用string_split()

select m.*, v.matched_count
from monitor m outer apply
     (select count(*) as matched_count
      from string_split(m.models, ',') s join
           vehicles v
           on s.value = v.model and m.makes = v.makes
     ) v;

I would advise you to put your efforts into fixing the data model, though.不过,我建议您努力修复数据 model。

Here is a db<>fiddle. 是一个 db<>fiddle。

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

相关问题 如何使用 Apache Spark SQL 查询在字符串数组中搜索字符串? - How to search a string in an array of strings using Apache Spark SQL query? 将来自SQL查询的定界字符串另存为字符串数组 - Save delimited string from SQL query as string array 如何编写 redshift aws 查询以搜索逗号分隔值中的值 - How to write redshift aws query to search for a value in comma delimited values 如何用逗号分隔的ID字符串构建WHERE查询? - How to build a WHERE query from a comma delimited string of ids? 基于分隔字符串的 Postgres 查询 - Postgres Query based on Delimited String 如何使用SQL Server对定界字符串中的数字求和 - How to sum numbers in a delimited string using SQL Server 从 excel 中的列创建逗号分隔的字符串数组以在 VBA sql 查询中使用 - Create comma delimited string array from a column in excel to use in VBA sql query SQL Server:如何编写SQL Select查询以从包含定界数据的列中搜索数据? - SQL Server : how to write a SQL Select query to search a data from a column contains delimited data? Oracle-如何提取定界字符串 - Oracle - How to extract delimited string 字符串查询中的列在执行时没有被分隔 - Columns in string query not being delimited when executed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM