如何使用 SQL 将来自两个不同列的两个不同值与逗号“,”连接起来?
How to concatenate two different values from two different columns with comma " , " using TSQL?
我想知道如何使用 TSQL 连接来自 SQL table 的两个不同列的两个不同值?
如您所见,我想将这两个不同的列 X 和 Y 连接起来,从而产生后续列 table:
这里应该使用哪个查询?
您可以简单地使用 +
来连接字符。
查询
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;
如果数据类型是数字类型(int、bigint、tinyint、smallint 等),那么您需要在连接之前将其转换为字符串。如果数据类型是 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
您可以将concat
用作
SELECT
Source, QtyPrevious, QtyToday, ProductPrevious, ProductToday,
AvaDatePr, AvaDateToday, Clusters, CONCAT(X, '', Y) as Z
from your_table_name;
我想知道如何使用 TSQL 连接来自 SQL table 的两个不同列的两个不同值?
如您所见,我想将这两个不同的列 X 和 Y 连接起来,从而产生后续列 table:
这里应该使用哪个查询?
您可以简单地使用 +
来连接字符。
查询
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;
如果数据类型是数字类型(int、bigint、tinyint、smallint 等),那么您需要在连接之前将其转换为字符串。如果数据类型是 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
您可以将concat
用作
SELECT
Source, QtyPrevious, QtyToday, ProductPrevious, ProductToday,
AvaDatePr, AvaDateToday, Clusters, CONCAT(X, '', Y) as Z
from your_table_name;