2016-12-16 43 views
0

我已经经历了一次,并以百万种不同的方式看到了这个问题,但没有一个答案似乎符合我的特殊需求,所以我希望有人能够提供帮助。SQL在单行中总结多行

我有一个表像下面:

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 
---------- 
+1

标签与正在使用的数据库你的问题。 –

+0

可能的重复http://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server – Anand

回答

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; 
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