繁体   English   中英

如何搜索 SQL 表格列文本并选择字符串或返回最高数字

[英]How to Search SQL table column text and pick out a string or return the highest number

我在 SQL 表中有一个列,如下所示。 它有年龄组信息,但非常随机:

Table1
Text
Males 40Y to 50Y
Mixed Sex 35 to 40
21Y only
Year7 boys
Year10 girls
Grade1
Random Text

我有另一个表格对一些年龄组数据进行分类:

Lookup Table
Keywords      Age
Year7          13
Year10         16
Grade1         6

我的最终目标是在原始表中添加一列 Age。 我想先查找Lookup Table ,然后如果没有匹配项,则查找字符串中的最高数字。 如果在那之后没有匹配,我想返回数字 1 以便我的结束表看起来像:

Text                    Age
Males 40Y to 50Y         50
Mixed Sex 35 to 40       40
21Y only                 21
Year7 boys               13
Year10 girls             16
Grade1                   6
Random Text              1

目前这超出了我的能力范围,因此请寻求一些帮助来解决此问题,因此将不胜感激。 非常感谢!!

根据您的示例数据,您可以使用如下逻辑:

select t.text, coalesce(l.age, x.num, 1) as age
from t cross apply
     (select max(try_convert(int, replace(s.value, 'Y', ''))) as num
      from string_split(t.text, ' ') s
     ) x left join
     lookup l
     on t.text like concat('%', l.keyword, '%');

请注意,这假定最大值是一个数字本身或后跟“Y”——这适用于您的示例数据。

是一个 db<>fiddle。

暂无
暂无

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

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