【问题标题】:How to concatenate two different values from two different columns with comma " , " using TSQL?如何使用 SQL 用逗号“,”连接来自两个不同列的两个不同值?
【发布时间】:2022-01-24 14:01:35
【问题描述】:

我想知道如何使用 TSQL 连接来自 SQL 表的两个不同列的两个不同值?

如您所见,我想将这两个不同的列 X e Y 连接起来,得到以下列表:

这里应该使用哪个查询?

【问题讨论】:

  • 问题是:你为什么要首先这样做?一般来说,格式应该留给客户端语言。
  • 提供数据集而不是附上截图。复制相同的数据集非常耗时。
  • 是否有任何列的数据类型不是pixel? “NULL”是图片、字符串还是null

标签: sql sql-server tsql concatenation coalesce


【解决方案1】:

如果数据类型是数字类型(int、bigint、tinyint、smallint 等),那么您需要在连接之前将其转换为字符串。如果数据类型是string(varchar,char,nvarchar,nchar) 那么可以直接使用concat函数

select concat(cast(column_1 as varchar) ,cast(column_2 as varchar))

select concat(column_1,column_2)

另一种解决方法,如果列是字符串数据类型,那么

select column_1+column_2

样本

with cte as (select 1 as id, 'name' as Field1, 'job' as Field2, '1test1' as Field1value , '2test1' as Field2value 
union select 2 as id, 'name' as Field1, 'job' as Field2, '1test1' as Field1value , '2test2' as Field2value 
union select 2 as id, 'age' as Field1, 'town' as Field2, '13' as Field1value , 'town1' as Field2value )
select 'select percentage from table2 where '+Field1+' ='+ ''''+Field1value+ ''''+' and '+Field2+' = '+  ''''+Field2value+ '''' from cte

结果

注意:任何一列中的空值都会导致结果为空

【讨论】:

    【解决方案2】:

    你可以使用concat作为

    SELECT 
        Source, QtyPrevious, QtyToday, ProductPrevious, ProductToday, 
        AvaDatePr, AvaDateToday, Clusters, CONCAT(X, '', Y) as Z 
    from your_table_name;
    

    【讨论】:

      【解决方案3】:

      您可以简单地使用+ 来连接字符。

      查询

      select *, x + ',' + y as z
      from your_table_name;
      

      如果任何列中有空值,则连接结果为null 值。

      处理任意列中的null

      查询

      select *,
      case 
        when x is null and y is not null then y
        when y is null and x is not null then x
        when x is null and y is null then null
        else x + ',' + y end as z
      from your_table_name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 2017-02-23
        • 1970-01-01
        • 2018-04-27
        • 2020-02-04
        • 1970-01-01
        相关资源
        最近更新 更多