如何将垂直数据透视到具有可变行长度的水平数据SQL?

时间:2013-04-10 16:47:56

标签: sql sql-server-2005 pivot unpivot

好的,我有下表。

Name    ID  Website

Aaron | 2305 |  CoolSave1


Aaron | 8464 |  DiscoWorld1


Adriana |   2956 |  NewCin1


Adriana |   5991 |  NewCin2


Adriana | 4563  NewCin3

我想将其转换为以下方式。

Adriana  |  2956 |  NewCin1 |   5991 |  NewCin2 | 4563  | NewCin3


Aaron | 2305 | CoolSave1 |  8464 |  DiscoWorld | NULL | NULL    

正如您所看到的,我正在尝试从第一个表中获取名字,并使用与该名称相关联的所有ID /网站创建一行。问题是,有可变数量的网站可能与每个名称相关联。为了解决这个问题,我想制作一个表格,其中字段数等于最大行项目,然后对于后续的行项目,在没有足够数据的情况下插入NULL。

1 个答案:

答案 0 :(得分:5)

为了获得结果,您需要将UNPIVOT和PIVOT函数同时应用于数据。 UNPIVOT将获取列(ID,网站)并将它们转换为行,一旦完成,您就可以将数据PIVOT回到列中。

UNPIVOT代码将类似于以下内容:

select name,
  col+'_'+cast(col_num as varchar(10)) col,
  value
from
(
  select name, 
    cast(id as varchar(11)) id, 
    website,
    row_number() over(partition by name order by id) col_num
  from yt
) src
unpivot
(
  value
  for col in (id, website)
) unpiv;

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

|    NAME |       COL |       VALUE |
-------------------------------------
|   Aaron |      id_1 |        2305 |
|   Aaron | website_1 |   CoolSave1 |
|   Aaron |      id_2 |        8464 |
|   Aaron | website_2 | DiscoWorld1 |

如您所见,我将row_number()应用于unpivot之前的数据,行号用于生成新的列名。 UNPIVOT中的列也必须具有相同的数据类型,我将cast应用于子查询中的id列,以便在数据透视之前将数据转换为varchar

然后在PIVOT中使用col值。数据取消后,您应用PIVOT功能:

select *
from
(
  select name,
    col+'_'+cast(col_num as varchar(10)) col,
    value
  from
  (
    select name, 
      cast(id as varchar(11)) id, 
      website,
      row_number() over(partition by name order by id) col_num
    from yt
  ) src
  unpivot
  (
    value
    for col in (id, website)
  ) unpiv
) d
pivot
(
  max(value)
  for col in (id_1, website_1, id_2, website_2, id_3, website_3)
) piv;

请参阅SQL Fiddle with Demo

如果您拥有有限或已知数量的值,则上述版本效果很好。但是如果行数未知,那么您将需要使用动态SQL来生成结果:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME( col+'_'+cast(col_num as varchar(10))) 
                    from
                    (
                      select row_number() over(partition by name order by id) col_num
                      from yt
                    ) t
                    cross apply
                    (
                      select 'id' col union all
                      select 'website'
                    ) c
                    group by col, col_num
                    order by col_num, col
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT name,' + @cols + ' 
            from 
            (
               select name,
                col+''_''+cast(col_num as varchar(10)) col,
                value
              from
              (
                select name, 
                  cast(id as varchar(11)) id, 
                  website,
                  row_number() over(partition by name order by id) col_num
                from yt
              ) src
              unpivot
              (
                value
                for col in (id, website)
              ) unpiv
            ) x
            pivot 
            (
                max(value)
                for col in (' + @cols + ')
            ) p '

execute(@query);

SQL Fiddle with Demo。两个版本都给出了结果:

|    NAME | ID_1 | WEBSITE_1 | ID_2 |   WEBSITE_2 |   ID_3 | WEBSITE_3 |
------------------------------------------------------------------------
|   Aaron | 2305 | CoolSave1 | 8464 | DiscoWorld1 | (null) |    (null) |
| Adriana | 2956 |   NewCin1 | 4563 |     NewCin3 |   5991 |   NewCin2 |