我在SQL表中有一列,如下所示。它具有年龄组信息,但非常随机:
Table1
Text
Males 40Y to 50Y
Mixed Sex 35 to 40
21Y only
Year7 boys
Year10 girls
Grade1
Random Text
我还有另一个分类年龄组数据some的表:
Lookup Table
Keywords Age
Year7 13
Year10 16
Grade1 6
我的最终目标是在“年龄”原始表中添加一列。我想先查找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)
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, '%');