-2

我一直在寻找一种方法来显示多个列中的一行,一个单元格。它的内容用逗号分隔。

例如,而不是:

ProjectID      Label
————           ——–
1200           label1
1200           label2
1200           label3

我希望我的查询结果如下所示:

ProjectID                      1        2        3
————                   ——– 
1200                          label1  label2, label3

提前致谢

4

1 回答 1

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;

这是使用枢轴的解决方案:

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
于 2013-05-25T12:50:23.247 回答