繁体   English   中英

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

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

我正在尝试搜索与分隔字符串中的值匹配的记录列。

我有两张看起来像这样的桌子

车辆

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

监视器

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

我想要达到的目标如下:

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

使用以下查询,我可以获得单数字符串的匹配项,但我不确定如何拆分逗号以搜索单个模型。

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

(我使用的是非常 SQL Server 2016 但是我无权创建自定义函数或变量)

如果你被这个数据 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;

不过,我建议您努力修复数据 model。

是一个 db<>fiddle。

暂无
暂无

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

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