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