将行转换为SQL Server 2008 R2中的列

我怎么转这个:

和这个:

进入这个:

在SQL Server 2008 R2中?

这个问题非常类似于PIVOT rows to columns with more than 1 value returned,您需要将行中的字符串数据聚合到列中.我将修改该答案,以演示如何将数据转换为最终结果.

由于您正在聚合字符串值,因此您需要应用min()或max()聚合函数,但为了使最终结果显示多行,您需要强制执行多行.

为此,您需要使用row_number()为名称中的每个参数生成唯一的序列号.应用PIVOT函数时,此编号将用于分组,您将生成多行:

select Car, Truck, Bicycle
from
(
  select vt.name, vp.parameter,
    row_number() over(partition by vt.name
                      order by vt.id) seq
  from vehicle_types vt
  left join vehicle_parameters vp
    on vt.id = vp.vehicletype
) d
pivot
(
  max(parameter)
  for name in (Car, Truck, Bicycle)
) piv;

SQL Fiddle with Demo.

这也可以使用带有CASE表达式的聚合函数编写:

select 
  max(case when name = 'Car' then parameter end) Car,
  max(case when name = 'Truck' then parameter end) Truck,
  max(case when name = 'Bicycle' then parameter end) Bicycle
from
(
  select vt.name, vp.parameter,
    row_number() over(partition by vt.name
                      order by vt.id) seq
  from vehicle_types vt
  left join vehicle_parameters vp
    on vt.id = vp.vehicletype
) d
group by seq;

SQL Fiddle with Demo.

如果你有一个已知数量的名称,上面两个版本是很好的,那么你可以硬编码查询,但如果你没有,那么你将不得不使用动态SQL:

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

select @cols = STUFF((SELECT ',' + QUOTENAME(name) 
                    from vehicle_types
                    group by id, name
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' 
             from 
             (
                select vt.name, vp.parameter,
                  row_number() over(partition by vt.name
                                    order by vt.id) seq
                from vehicle_types vt
                left join vehicle_parameters vp
                  on vt.id = vp.vehicletype
            ) x
            pivot 
            (
                max(parameter)
                for name in (' + @cols + ')
            ) p '

execute sp_executesql @query;

SQL Fiddle with Demo.所有版本都给出了结果:

|    CAR |            TRUCK |    BICYCLE |
|--------|------------------|------------|
|   make |          maxload |      frame |
|   year | hasconcretemixer |     isroad |
| engine |           (null) | ismountain |
https://stackoverflow.com/questions/20119162/transpose-rows-into-columns-in-sql-server-2008-r2

转载注明原文:将行转换为SQL Server 2008 R2中的列