SQL汇总了一行中的多行

时间:2016-12-16 17:06:10

标签: sql pivot row

我已经通过并以百万种不同的方式看到了这个问题,但没有一个答案似乎符合我的特殊需求,所以我希望有人可以提供帮助。

我有一张如下表:

URN | CustomerID | Selection
----------
1 | 1 | 16A
----------
2 | 1 | 16B
----------
3 | 1 | 16C
----------
4 | 2 | 16A
----------
5 | 2 | 16C
----------
6 | 1 | 16D
----------
6 | 1 | 16E
----------

我想要的是一个如下所示的导出表或查询(限于5列供选择):

CustomerID | Selection 1 | Selection 2 | Selection 3 | Selection 4 | Selection 5
----------
1 | 16A | 16B | 16C | 16D | 16E
----------
2 | 16A | 16C 
----------

2 个答案:

答案 0 :(得分:0)

您可以使用带有透视方法的ANSI标准row_number()来执行此操作。我更喜欢条件聚合:

select CustomerID,
       max(case when seqnum = 1 then selection end) as selection_1,
       max(case when seqnum = 2 then selection end) as selection_2,
       max(case when seqnum = 3 then selection end) as selection_3,
       max(case when seqnum = 4 then selection end) as selection_4,
       max(case when seqnum = 5 then selection end) as selection_5
from (select t.*,
             row_number() over (partition by CustomerID order by urn) as seqnum
      from t
     ) t
group by CustomerID;

答案 1 :(得分:0)

如果您需要动态并假设SQL Server

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(concat('Selection ',Row_Number() over (Partition By CustomerID Order By URN) )) From YourTable For XML Path('')),1,1,'') 
Select  @SQL = '
 Select [CustomerID],' + @SQL + '
  From  (Select CustomerID,Selection,Col=concat(''Selection '',Row_Number() over (Partition By CustomerID Order By URN) ) From YourTable) A
 Pivot (Max([Selection]) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);

返回

CustomerID  Selection 1 Selection 2 Selection 3 Selection 4 Selection 5
1           16A         16B         16C         16D         16E
2           16A         16C         NULL        NULL        NULL
相关问题