2013-11-01 88 views
3

我想基於其他列中的數據是相同的,將一列數據分成多個(在必要的情況下爲1到5之間)。
這是我的數據的查詢之後的示例:SQL Server將一列分成多列

FirstName LastName StreetName StreetNumber AccountNumber 
John   Smith  Fake St  123    10 
John   Smith  Fake St  123    20 
John   Smith  Fake St  123    30 
John   Smith  Fake St  123    40 

這是基於一個事實,即同一個人在同一個地址可以有多個賬戶,高達5。我需要我的結果怎麼看像:

FirstName LastName StreetName StreetNumber AccountNumber1 AccountNumber2 AccountNumber3 AccountNumber4 AccountNumber5 
John   Smith  Fake St  123    10    20    30    40    NULL 

所以我需要使用accountNumber列分成基礎上的名稱/地址是相同的標準多列。我想創建5個新列,並且任何空字段都是NULL值。誰能幫忙?

回答

4

你可以用簡單的數據透視:

with cte as (
    select 
     *, 
     'AccountNumber' + 
     cast(
      row_number() 
      over(
       partition by [FirstName], [LastName], [StreetName], [StreetNumber] 
       order by AccountNumber 
     ) 
     as nvarchar(max)) as rn 
    from Table1 
) 
select * 
from cte 
pivot (
    max(AccountNumber) 
    for rn in (
     [AccountNumber1], 
     [AccountNumber2], 
     [AccountNumber3], 
     [AccountNumber4], 
     [AccountNumber5] 
    ) 
) as p; 

,或者你可以用手轉動:

with cte as (
    select 
     *, 
     row_number() 
     over(
      partition by [FirstName], [LastName], [StreetName], [StreetNumber] 
      order by AccountNumber 
     ) as rn 
    from Table1 
) 
select 
    [FirstName], [LastName], [StreetName], [StreetNumber], 
    max(case when rn = 1 then AccountNumber end) as AccountNumber1, 
    max(case when rn = 2 then AccountNumber end) as AccountNumber2, 
    max(case when rn = 3 then AccountNumber end) as AccountNumber3, 
    max(case when rn = 4 then AccountNumber end) as AccountNumber4, 
    max(case when rn = 5 then AccountNumber end) as AccountNumber5 
from cte 
group by [FirstName], [LastName], [StreetName], [StreetNumber] 

sql fiddle demo

+0

謝謝你的快速和正確的反應! – Jason