首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将Server中的所有行转换为列

将Server中的所有行转换为列
EN

Stack Overflow用户
提问于 2018-09-26 10:34:04
回答 2查看 89关注 0票数 0

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

当前结果:

代码语言:javascript
复制
PortCode    CarCode
------------------------
AAB         A5
ADR         BH
SAN         QQ

预期结果:

代码语言:javascript
复制
PortCode   CarCode   PortCode  CarCode   PortCode   CarCode
-----------------------------------------------------------
AAB        A5        ADR       BH        SAN        QQ

曾尝试过与PIVOT,但没有帮助。

谁能给我解释一下,怎么实现呢?

EN

Stack Overflow用户

回答已采纳

发布于 2018-09-26 10:36:19

如果我没听错,

代码语言:javascript
复制
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)
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52515697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档