簡體   English   中英

如何使用 TSQL 用逗號“,”連接來自兩個不同列的兩個不同值?

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

我想知道如何使用 TSQL 連接 SQL 表中兩個不同列的兩個不同值?

在此處輸入圖像描述

如您所見,我想將這兩個不同的列 X e Y 連接起來,從而得到以下列表:

在此處輸入圖像描述

這里應該使用哪個查詢?

如果數據類型是數字類型(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)

另一種解決方法,如果列是字符串數據類型,則

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

結果

在此處輸入圖像描述

注意:任何一列中的 null 值的結果將是 null

您可以簡單地使用+來連接字符。

詢問

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

如果任何列中有 null 值,則連接結果為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;

您可以使用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