来自多个列的透视值

ajsxfq5m  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(306)

在sql server数据库中具有下表:

我的目标是根据类型列旋转“左”、“右”、“中”,并得出以下输出:

我只能使用pivot查询对一列(如左)执行上述操作,如下所示:
我得到的订单是:

需要帮助来驱动第二个图屏幕截图中给出的表。
创建表的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
wsxa1bj1

wsxa1bj11#

你可以试试下面的方法-
演示

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;

相关问题