将两列中的值与SQL连接起来,SQL之间用“/quot;”分隔&引用;

将两列中的值与SQL连接起来,SQL之间用“/quot;”分隔&引用;,sql,join,Sql,Join,我需要将一列中的列和用破折号分隔的值连接起来。 但只有当两列都有值时,情况并非总是如此。在这种情况下,我只想移动该值并将其单独显示在结果列中。 我如何才能最好地实现这一点 您需要字符串连接。表达这一点的标准方式是: select col1, col2, case when col1 is not null and col2 is not null then col1 || '/' || col2 else coalesce(col1, col2)

我需要将一列中的列和用破折号分隔的值连接起来。 但只有当两列都有值时,情况并非总是如此。在这种情况下,我只想移动该值并将其单独显示在结果列中。 我如何才能最好地实现这一点


您需要字符串连接。表达这一点的标准方式是:

select col1, col2,
    case 
        when col1 is not null and col2 is not null then col1 || '/' || col2
        else coalesce(col1, col2)
    end as result
from mytable
| |
是字符串连接的标准运算符-不同数据库的语法可能不同(但总是有一个等效的运算符或函数)

一些数据库实现了
concat_ws()
,而在一些数据库中,它会忽略
null
值,这使您可以将整个
大小写表达式简化为:

concat_ws('/', col1, col2) as result

支持这种语法的数据库示例是MySQL。

只需使用
case
表达式:

select case when col1 is not null and col2 is not null then col1 + ' / ' + col2
            when col1 is not null then col1
            when col2 is not null then col2
            else null end
from myTable;
请注意,字符串连接可能因RDBMS而异,例如在我使用的MySql中,
concat(col1,“/”,col2)
(在fiddle中)

顺便说一句,
/
不是破折号,而是斜杠(正斜杠)


阿哈恩!!您可以简单地使用
trim
函数,如下所示(Oracle示例)


TRIM
功能在每个数据库中都可用。

多个数据库支持
concat_ws()
,这是最简单的方法:

concat_ws('/', column1, column2)
在那些不需要的情况下,您需要使用特定于数据库的函数。标准SQL构造是:

substring('/' || column1 || '/' || column2 from 2)

@谢谢,更正。您使用的是哪种DBMS产品?“SQL”只是所有关系数据库使用的查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加<代码>合并(col1 | |'/'| | col2,col1,col2)
Postgres也以这种方式支持
concat_ws()
substring('/' || column1 || '/' || column2 from 2)