简体   繁体   English

如何使用 TSQL 用逗号“,”连接来自两个不同列的两个不同值?

[英]How to concatenate two different values from two different columns with comma " , " using TSQL?

I would like to know how to concatenate two different values from two different columns from a SQL table using TSQL?我想知道如何使用 TSQL 连接 SQL 表中两个不同列的两个不同值?

在此处输入图像描述

As you can see, I would like to concatenate those two different columns X e Y, resulting in the follow column table:如您所见,我想将这两个不同的列 X e Y 连接起来,从而得到以下列表:

在此处输入图像描述

Which query should be used here?这里应该使用哪个查询?

if the datatype is numeric types(int,bigint, tinyint,smallint,etc) then you need to cast it to string before you concatenate.如果数据类型是数字类型(int、bigint、tinyint、smallint 等),那么您需要在连接之前将其转换为字符串。 if the datatype is string(varchar,char,nvarchar,nchar) then you can directly use concat function如果数据类型是 string(varchar,char,nvarchar,nchar) 那么你可以直接使用concat function

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

select concat(column_1,column_2)

another workaround, if the columns are string datatype, then另一种解决方法,如果列是字符串数据类型,则

select column_1+column_2

sample样本

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

result结果

在此处输入图像描述

Note: null value in any one column will have result as null注意:任何一列中的 null 值的结果将是 null

You can simply use + to concatenate charcaters.您可以简单地使用+来连接字符。

Query询问

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

If there is a null value in any of the columns, then the concatenation results to a null value.如果任何列中有 null 值,则连接结果为null值。

To handle the null value in any of the column处理任意列中的null

Query询问

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;

You can use concat as您可以使用concat作为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM