Search code examples
sqlsql-serversql-server-2008pivotunpivot

SQL Pivot or something else?


I have a pre-existing table (so I can't change this table) like this:

Company     GLSeg1     GLSeg2     GLSeg3
XXX         00003      NULL       00001
YYY         00002      00004      NULL

I would like to create a temp table like this, selecting for just one company:

When querying for XXX the table should look like this:

GLSeg       Value
1           00003
2           NULL
3           00001

When querying for YYY the table should look like this:

GLSeg       Value
1           00002
2           00004
3           NULL

I have looked at the pivot function but am not seeing a way to create the temp table as needed.


Solution

  • using cross apply(values ..) to unpivot your data:

    select t.Company, v.GLSeg, v.Value
    from t
      cross apply (values 
        (1,glseg1),(2,glseg2),(3,glseg3)
      ) v (GLSeg,Value)
    

    rextester demo: http://rextester.com/ZKTD58113

    returns:

    +---------+-------+-------+
    | Company | GLSeg | Value |
    +---------+-------+-------+
    | xxx     |     1 | 00003 |
    | xxx     |     2 | NULL  |
    | xxx     |     3 | 00001 |
    | yyy     |     1 | 00002 |
    | yyy     |     2 | 00004 |
    | yyy     |     3 | NULL  |
    +---------+-------+-------+
    

    For just one company:

    select v.GLSeg, v.Value
    from t
      cross apply (values 
        (1,glseg1),(2,glseg2),(3,glseg3)
      ) v (GLSeg,Value)  
    where t.company = 'xxx'
    

    returns:

    +-------+-------+
    | GLSeg | Value |
    +-------+-------+
    |     1 | 00003 |
    |     2 | NULL  |
    |     3 | 00001 |
    +-------+-------+