首页 > 解决方案 > 透视多列中的值

问题描述

在 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

标签: sqlsql-serverpivot

解决方案


你可以试试下面的方法——

演示

 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;

推荐阅读