首页 > 解决方案 > 在 SQL Server 中将所有行转换为列

问题描述

尝试在 SQL Server 中将行转换为多列,如下所示:

当前结果:

PortCode    CarCode
------------------------
AAB         A5
ADR         BH
SAN         QQ

预期结果:

PortCode   CarCode   PortCode  CarCode   PortCode   CarCode
-----------------------------------------------------------
AAB        A5        ADR       BH        SAN        QQ

试过PIVOT但没有帮助。

谁能解释一下,如何实现?

标签: sqlsql-serverpivotpivot-table

解决方案


如果我理解正确,

select max(case when seqnum = 1 then portcode end) as portcode_1,
       max(case when seqnum = 1 then carcode end) as carcode_1,
       max(case when seqnum = 2 then portcode end) as portcode_2,
       max(case when seqnum = 2 then carcode end) as carcode_2,
       max(case when seqnum = 3 then portcode end) as portcode_3,
       max(case when seqnum = 3 then carcode end) as carcode_3       
from (select t.*, row_number() over (order by (select null)) as seqnum
      from t
     ) t;

笔记:

  • 这不是动态的。它产生 6 列(但您可以将相同的想法用于动态查询)。
  • 结果的顺序是不确定的。SQL 表表示无序集。如果您希望列按特定顺序排列,请替换(select null)为适当的列。

推荐阅读