sql - 透视多列中的值
问题描述
在 SQL Server DB 中有下表:
我的目标是根据类型列旋转“左”、“右”、“中心”并得出以下输出:
我只能使用 Pivot Query对一列(比如Left )执行上述操作,如下所示:
我得到的 O/P 是:
需要帮助来驱动表格,如第二个图屏幕截图所示。
用于创建表的 DDL 脚本:
Create Table ssis.PivotTable
(
[System] VARCHAR(20)
, Corridor VARCHAR(20)
, RouteId VARCHAR(20)
, [Left] VARCHAR(20)
, [Right] VARCHAR(20)
, [Centre] VARCHAR(20)
, [Type] VARCHAR(20))
GO
INSERT INTO ssis.PivotTable VALUES
('Disrupted', NULL, 'WFG-231', '2', '3', '4', 'ABW')
GO
INSERT INTO ssis.PivotTable VALUES
('Disrupted', NULL, 'WFG-231', '3', '4', '4', 'AwW')
GO
INSERT INTO ssis.PivotTable VALUES
('Disrupted', NULL, 'WFG-231', '3', '2', '3', 'AEG')
我写的透视查询
SELECT [System], Corridor, [RouteId], PivotTable.ABW AS ABW_Left, PivotTable.AwW AS AWW_Left, PivotTable.AEG AS AEG_Left
FROm (SELECT [System], Corridor, [RouteId],[Left], [Type] FROM ssis.PivotTable) AS SourceQuery
PIVOT
(MAX([Left]) FOR [Type] in (ABW, AwW, AEG)) AS PivotTable
解决方案
你可以试试下面的方法——
select [System], Corridor, [RouteId],
[ABW_Left], [ABW_Right], [ABW_Center], [AwW_Left],
[AwW_Right], [AwW_Center], [AEG_Left], [AEG_Right],[AEG_Center]
from
(
select [System], Corridor, [RouteId],
col = type+'_'+col,
value
from PivotTable t
cross apply
(
select 'Reft', [Left] union all
select 'Right', [Right] union all
select 'Center', [Centre]
) c (col, value)
) d
pivot
(
max(value)
for col in ([ABW_Left], [ABW_Right], [ABW_Center], [AwW_Left],
[AwW_Right], [AwW_Center], [AEG_Left], [AEG_Right],[AEG_Center])
) piv;
推荐阅读
- c# - EF Core 枚举列表
- apache-zookeeper - CachedModeledFramework 初始化时如何通知
- opentext - OpenText Content Server how to get folder ID with path using REST API?
- date - 在 Vega-Lite 中为日期添加日期
- ios - 为什么 SwiftUI 的 macOS 上的 EKCalendarChooser 中没有显示 Google 日历
- python - PyQT QThread 遵循线程执行顺序(等待)
- angular - 服务如何订阅当前路由的 ParamMap?
- flutter - 将自定义小部件动态添加到列表中 - Flutter
- google-cloud-ai-platform-pipelines - 如何在 AI Platform Pipelines 上使用 GPU
- javascript - 如何在反应中从某些页面中删除导航栏