我一直在寻找一种方法来显示多个列中的一行,一个单元格。它的内容用逗号分隔。
例如,取代:
ProjectID Label
———— ——–
1200 label1
1200 label2
1200 label3
我希望我的查询结果如下:
ProjectID 1 2 3
———— ——–
1200 label1 label2, label3
提前致谢
答案 0 :(得分:0)
这比使用pivot
更具挑战性,但只是一点点。问题是你没有一个列来指定标签所在的 ,所以你必须添加它。
以下是使用聚合的解决方案:
with t as (
select t.*, row_number() over (partition by ProjectId order by label) as seqnum
from t
)
select ProjectId,
max(case when seqnum = 1 then label end) as [1],
max(case when seqnum = 2 then label end) as [2],
max(case when seqnum = 3 then label end) as [3]
from t
group by ProjectId;
以下是使用pivot的解决方案:
with t as (
select t.*, row_number() over (partition by ProjectId order by label) as seqnum
from t
)
select ProjectId, [1], [2], [3]
from t
pivot (max(label) for seqnum in ([1], [2], [3])
) as pvt