Search code examples
sqlsql-servert-sqlunpivot

SQL Server 2008 Unpivot with Given Condition


I am really stuck for this problem, which I think could be solved using unpivot but I really have no clue how it should be constructed. I have the following table:

TableName       ColumnName        ColumnValue
----------------------------------------------
Table1          ColumnA            1
Table1          ColumnB            2
Table1          ColumnC            3
Table2          ColumnA            4
Table2          ColumnD            5

I would like to get the following result:

TableName        Column1         Column2        ColumnAValue        ColumnBValue
---------------------------------------------------------------------------------
Table1           ColumnA         ColumnB        1                   2
Table2           ColumnA         ColumnD        4                   5

I am given the following table:

TableName        Column1        Column2
---------------------------------------
Table1           ColumnA        ColumnB
Table2           ColumnA        ColumnD

Solution

  • If I understand correctly... the "Given Table" is the KEY

    Example

    Select G.* 
          ,ColumnAValue = A.ColumnValue
          ,ColumnBValue = B.ColumnValue
     From  GivenTable G
     Left  Join YourTable A on G.TableName=A.TableName and G.Column1=A.ColumnName
     Left  Join YourTable B on G.TableName=B.TableName and G.Column2=B.ColumnName
    

    Returns

    TableName   Column1   Column2   ColumnAValue    ColumnBValue
    Table1      ColumnA   ColumnB   1               2
    Table2      ColumnA   ColumnD   4               5