2017-09-13 38 views
1

我有值轉換相交成兩個逗號分隔值

letter number 
A  1 
A  2 
A  3 
B  1 
B  2 

兩列我想兩個聚合,逗號分隔的,代表着不同的組letternumber的交點的值。

e.g

letters numbers 
A,B  1,2 
A  3 
+0

您是否嘗試過的查詢但你可以與我們分享級聯的number欄目組? –

+2

在這裏檢查你的答案 - https://stackoverflow.com/questions/12671117/comma-separated-values-with-sql-query – Rojelo

+2

@Emil如果你的輸入包含C和2的更多行,你期望什麼結果?或者第一列總是隻有兩個不同的值? – sepupic

回答

2

我所做的是,首先由number列串連的letter列組。然後給出一個由連字母組成的行號分區,並按number排序。然後再由串聯

查詢

;with cte as(
    select * 
    from (
     select [number], stuff((
       select ', ' + [letter] 
       from [your_table_name] 
       where ([number] = t.[number]) 
       for xml path('') 
      ) 
      , 1, 2, '' 
     ) as letters 
     from [your_table_name] t 
     group by [number] 
    )t2 
) 
select [letters], stuff((
     select ', ' + cast(number as varchar(100)) 
     from cte 
     where ([letters] = t.[letters]) 
     for xml path('') 
    ) 
    , 1, 2, '' 
) as [numbers] 
from cte t 
group by [letters]; 

Find a demo here