用于组合1个表中多个行的SQL查询

时间:2013-04-26 02:32:57

标签: sql sql-server pivot

我正在寻找一些帮助,试图将具有公共ID的多行与SQL Server组合成一行。这是一个例子:

ID  Name   Number
1   Joe    1234
1   Marie  5678
1   Ron    2222
1   Tom    4444

希望查询显示:

ID  Name  Number  Name  Number  Name  Number  Name  Number
1   Joe   1234    Marie 5678    Ron   2222    Tom   4444

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 |