将两列的交集转换为两个以逗号分隔的值

时间:2017-09-13 06:13:51

标签: sql-server

我有两列值

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

我想要两个汇总的逗号分隔值,表示letternumber的不同交集。

e.g

letters numbers
A,B     1,2
A       3

1 个答案:

答案 0 :(得分:2)

我所做的是,首先将letter列组连接到number列。然后按照number的连接字母和顺序给出行号分区。然后再次通过连接

连接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