如何通过一个新列来表示列a和列b之间是否存在匹配

nlejzf6q  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(339)

我有一个查询,结果如下表所示:

ColumnX      ColumnY          
 apple     the apple is red   
 orange    orange tree is tall
 berry      the sky is blue

基本上要创建一个新列,检查columnx值是否在columny中被表示为“是”或“否”:

ColumnX      ColumnY               newColumn       
 apple     the apple is red            Yes
 orange    orange tree is tall         Yes
 berry      the sky is blue            No

我试过这样的方法:

case 
   when ColumnX like '%' + ColumnY + '%' then "Yes"
end as newColumn

无济于事。

ajsxfq5m

ajsxfq5m1#

你想要什么 like 相反的操作数。此外,应该使用单引号来定义字符串文字,而不是双引号。
所以:

select
    t.*,
    case when columnY like '%' + columnX + '%'
        then 'Yes'
        else 'No'
    end newColumn
from mytable t

你也可以使用 charindex() :

case when charindex(columnX, columnY) > 0 then 'Yes' else 'No' end
qojgxg4l

qojgxg4l2#

你可以用以下方法

SELECT *, CASE WHEN ColY LIKE CONCAT('%', ColX, '%')
               THEN 'Yes'
               ELSE 'No'
          END NewColumnUsingLike,
          CASE WHEN PATINDEX(CONCAT('%', ColX, '%'), ColY) > 0
               THEN 'Yes'
               ELSE 'No'
          END NewColumnUsingPatIndex,
          CASE WHEN CHARINDEX(ColX, ColY) > 0
               THEN 'Yes'
               ELSE 'No'
          END NewColumnUsingCharIndex
FROM
(
  VALUES
  ('apple',     'the apple is red'),   
  ('orange',    'orange tree is tall'),
  ('berry',     'the sky is blue')
) T(ColX, ColY);

在线演示

相关问题