我有两列值
letter number
A 1
A 2
A 3
B 1
B 2
我想要两个汇总的逗号分隔值,表示letter
和number
的不同交集。
e.g
letters numbers
A,B 1,2
A 3
答案 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 强>