Unpivot SQL或交叉应用表,其中行数据作为列标题,行数据作为列数据

时间:2017-06-29 11:05:54

标签: sql sql-server transpose unpivot cross-apply

我知道很多时候都会问这个问题,但我找不到我的数据结构的解决方案。但我确实遇到了以下文章An Alternative (Better?) Method to UNPIVOT (SQL Spackle)

我有下表,原始数据结果如下

    RowType | LocalDate | UTCDate | Target1 | Target2 | Target3
    KPIName     NULL        NULL     Feed1     Feed2     Feed3
    Balance     NULL        NULL    Product   Reagent    Water
    UoM         NULL        NULL       t        t          %
    ActiveDate 2017-01-01 2016-12-31   5.0     3.2        20

我想要实现的结果如下

KPIName | Balance | ActiveDate | UTCDate  | UoM | Value
 Feed1    Product   2017-01-01  2016-12-31  t     5.0
 Feed2    Reagent   2017-01-01  2016-12-31  t     3.2
 Feed3    Water     2017-01-01  2016-12-31  %     20

1 个答案:

答案 0 :(得分:0)

CREATE TABLE #Table1
    ([RowType] varchar(10), [LocalDate] varchar(10), [UTCDate] varchar(10), [Target1] varchar(7), [Target2] varchar(7), [Target3] varchar(5))
;

INSERT INTO #Table1
    ([RowType], [LocalDate], [UTCDate], [Target1], [Target2], [Target3])
VALUES
    ('KPIName', NULL, NULL, 'Feed1', 'Feed2', 'Feed3'),
    ('Balance', NULL, NULL, 'Product', 'Reagent', 'Water'),
    ('UoM', NULL, NULL, 't', 't', '%'),
    ('ActiveDate', '2017-01-01', '2016-12-31', '5.0', '3.2', '20')
;
 SELECT 
X.KPINAME,X.BALANCE,LOCALDATE,UTCDATE,X.UOM,X.VALUE
FROM #TABLE1
 CROSS APPLY (
    VALUES ('FEED1', 'PRODUCT','T',5.0)
    ,('FEED2', 'REAGENT','T',3.2)
    ,('FEED3', 'WATER','%',20)) X(KPINAME, BALANCE,UOM,VALUE)
    WHERE LOCALDATE IS NOT NULL