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

时间:2013-11-21 11:03:23

标签: sql sql-server-2008-r2 pivot

我该怎么做:

enter image description here

和此:

enter image description here

进入这个:

enter image description here

在SQL Server 2008 R2中?

1 个答案:

答案 0 :(得分:9)

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

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

要执行此操作,您需要使用row_number()parameter中的每个name生成唯一的序列号。当您应用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 |