将行转换为列

时间:2019-11-08 20:08:18

标签: sql sql-server pivot pivot-table

select ID, Vehicle from table

原始结果是

ID      Vehicle
--------------------
1       Car
1       Bike
1       Scooter
...
1       N.Product

我期望的结果

ID    Vehicle1   Vehicle2   Vehicle3  ....VehicleN
-----------------------------------------------------
1     Car         Bike       Scooter       N.Product

我浏览了与数据透视有关的示例,但它们没有帮助。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以使用row_number()进行透视或条件聚合:

select id,
       max(case when seqnum = 1 then vehicle end) as vehicle_1,
       max(case when seqnum = 2 then vehicle end) as vehicle_2,
       . . .
       max(case when seqnum = n then vehicle end) as vehicle_n
from (select t.*, 
             row_number() over (partition by id order by vehicle) as seqnum
      from t
     ) t
group by id;

这假定您知道结果集中所需的列数。如果不是这种情况,则需要使用动态SQL或将载具聚合为字符串。

答案 1 :(得分:0)

我通过创建一个临时表然后使用while循环,添加列和更新值来做到这一点