0

我正在寻求一些帮助,以尝试将具有公共 ID 的多行与 SQL Server 合并为 1 行。这是一个例子:

身份证号码
1乔1234
1 玛丽 5678
1 罗恩 2222
1 汤姆 4444

希望查询显示:

ID 姓名 号码 姓名 号码 姓名 号码 姓名 号码
1 乔 1234 玛丽 5678 罗恩 2222 汤姆 4444
4

2 回答 2

1
with data as (
    select *, row_number() over (partition by ID order by ID) as rowid
    from (
        values (1, 'Joe', 1234),
                (1, 'Marie', 5678),
                (1, 'Ron', 2222),
                (1, 'Tom', 4444)
    ) t (ID, Name, Number)
)
select t.ID, t.[1] as Name, t2.[1] as Number, t.[2] as Name, t2.[2] as Number, 
             t.[3] as Name, t2.[3] as Number, t.[4] as Name, t2.[4] as Number
from (
    select ID, Name, rowid
    from data
) d pivot (min(Name) for rowid in ([1], [2], [3], [4])) t
inner join (
    select ID, Number, rowid
    from data
) d2 pivot (min(Number) for rowid in ([1], [2], [3], [4])) t2 on t.ID = t2.ID
于 2013-04-26T08:20:08.050 回答
1

我建议同时应用 UNPIVOT 和 PIVOT 函数来获得结果。UNPIVOT 会将您的namenumber列转换为多行,然后您将应用 PIVOT 函数将其转换回列:

select *
from
(
  select id,
    col+'_'+cast(rn as varchar(10)) col,
    value
  from
  (
    select id, name, cast(number as varchar(10)) number,
      row_number() over(partition by id order by number) rn
    from yt
  ) src
  unpivot
  (
    value
    for col in (name, number)
  ) unpiv
) d
pivot
(
  max(value)
  for col in (name_1, number_1, name_2, number_2,
              name_3, number_3, name_4, number_4)
) piv;

请参阅SQL Fiddle with Demo。这给出了一个结果:

| ID | NAME_1 | NUMBER_1 | NAME_2 | NUMBER_2 | NAME_3 | NUMBER_3 | NAME_4 | NUMBER_4 |
--------------------------------------------------------------------------------------
|  1 |    Joe |     1234 |    Ron |     2222 |    Tom |     4444 |  Marie |     5678 |
于 2013-04-26T11:19:08.090 回答