从一个 SQL table 搜索文本并将其从另一个 SQL table 和 return 值匹配到新列

Search Text from one SQL table and match it from another SQL table and return values to a new column

我不确定如何解释这个标题,所以很抱歉。我希望获得有关如何实现以下目标的一些指导:

我有一个 table 具有以下内容:

[dbo].[TABLEA]
 Name          Text
John Smith      . Tall. Smart. Blonde.
Jack Smith      . Medium. Low Intelligence. Black.
Jess Smith      . Short. Smart. Brunette.
Josh Smith      . Tall. Average Intelligence. Blonde. Smart.

我有第二个 table 看起来像:

[dbo].[TABLEB]

Comment                         Major Category            Minor Category
. Tall.                         Height                     Tall
. Medium.                       Height                      Medium
. Short.                        Height                      Short
. Smart.                        Intelligence                Smart
. Average Intelligence.         Intelligence                Average
. Low Intelligence.             Intelligence                Low
. Blonde.                       Hair Colour                 Blonde
. Brunette.                     Hair Colour                 Brunette
. Black.                        Hair Colour                 Black

我正在尝试搜索 TABLEA 中的文本,然后将 Major Category 列中的信息添加到 Minor Category 列中。请注意,如果同一文本中出现两个次要类别,我很乐意 return 找到第一个。

我希望得到的输出是:

Name         Text                                           Height     Intelligence     Hair Colour
John Smith  . Tall. Smart. Blonde.                          Tall        Smart           Blonde
Jack Smith  . Medium. Low Intelligence. Black.              Medium      Low             Black
Jess Smith  . Short. Smart. Brunette.                       Short       Smart           Brunette
Josh Smith  . Tall. Average Intelligence. Blonde. Smart.    Tall        Average         Blonde

我有信心在 Excel 中做到这一点,但 SQL 对我来说是另一回事。任何指导将不胜感激!谢谢!

我认为这符合您的要求:

select a.*, bh.minor_category as height, bi.minor_category as intelligence
from tablea a outer apply
     (select top (1) b.*
      from tableb b
      where b.major_category = 'height' and
            a.text like concat('%', b.text, '%')
     ) bh outer apply
     (select top (1) b.*
      from tableb b
      where b.major_category = 'intelligence' and
            a.text like concat('%', b.text, '%')
     ) bi;