sql - 在 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
但没有帮助。
谁能解释一下,如何实现?
解决方案
如果我理解正确,
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)
为适当的列。
推荐阅读
- r - 如何在闪亮应用的侧边栏中设置同一行中的小部件之间的距离
- excel - 如何获得“选择案例以测试范围内的每个单元格?
- google-cloud-platform - 如何为每个“记录”类型字段删除 BigQuery 表中的 __key__ 列?
- node.js - Express.js /public 文件夹的 Kubernetes Ingress 重定向
- javascript - 以变量为参数的wordpress简码
- python - Sympy:如何使用第二个量化模块获得简化的换向器?
- c# - Visual Studio 中的项目 GUID
- java - 使用 Fabric8 的 Kubernetes 客户端 API
- python - 如何使用 2 个参考对包含列表的列表进行排序
- amazon-cloudformation - 无法使用依赖于 AWS Glue 中的爬网程序的控制台创建触发器