3

我正在尝试根据其他列中的数据相同,将一列数据拆分为多个(必要时在 1 到 5 之间)。
这是查询后我的数据示例:

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

1 回答 1

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

于 2013-11-01T20:05:22.690 回答