如果 column1 不包含 column2,则连接 column1 和 column2

Concat column1 and column2 if column1 does not contain column2

如何从 column1column2 中获取 concat 列?

| column1  | column2 | concat
| -----------------------------
| 20KM     | NULL    | 20KM
| 20KM     | KM      | 20KM
| 20K      | M       | 20KM

我只想连接 column1column2 如果 column1 不包含 column2.

您可以使用:

concat(column1, (case when position(column2 in column1) = 0 then column2 end))

对于 Firebird,您可以将 CASE with CONTAINING or POSITION 与连接运算符 (||) 结合使用:

case when column2 is null or column1 containing column2 then column1 else column1 || column2 end

column1 || case when column1 not containing column2 then column2 else '' end

看到这个 Firebird dbfiddle。使用位置会类似。

PostgreSQL 没有 CONTAINING,因此您可以使用 POSITION(column2 IN column1) > 0 而不是 CONTAININGPOSITION(column2 IN column1) = 0 for NOT CONTAINING:

case when column2 is null or position(column2 in column1) > 0 then column1 else column1 || column2 end

column1 || case when position(column2 in column1) = 0 then column2 else '' end

看到这个 PostgreSQL dbfiddlePOSITION 的这种用法也适用于 Firebird。

我会使用带有 LIKE 的 CASE 表达式:

select case 
        when column2 is null or column1 like '%'||column2||'%' then column1
        else column1||column2
      end
from the_table