如何搜索 SQL table 列文本并挑选出字符串或 return 最高数字

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

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

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

我有另一个 table 分类 一些 年龄组数据:

Lookup Table
Keywords      Age
Year7          13
Year10         16
Grade1         6

我的最终目标是在原来的 table Age 中添加一列。我想先查找 Lookup Table ,然后如果没有匹配项,则在字符串中找到最大的数字。如果在那之后没有匹配,我想 return 数字 1 这样我的结尾 table 看起来像:

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" -- 这适用于您的示例数据。

Here 是一个 db<>fiddle.