2016-12-16 45 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