Search code examples
sqlsql-servertransposeunpivotcross-apply

Unpivot SQL OR Cross-Apply table with row data as column headings and row data as column data


I know this question has been asked many time but I have not been able to find a solution with my data structure. I did however come across the following article An Alternative (Better?) Method to UNPIVOT (SQL Spackle).

I have the following table with the raw data result as follows

    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

The result I am trying to achieve is the following

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

Solution

  • 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