Search code examples
sqlsql-serverunpivot

SQL Unpivot Text Contents


I have seen a number of examples covering pivoting a table, but none which cover text that has no standard format.

For example sake, my table would appear like the following (we have several "note" columns)

PK_ID  JOB_ID  NOTE1           NOTE2
-----  ------  --------------  -----------------
1      53      Some note here  Another note here
2      105     Noted text      [NULL]
3      105     [NULL]          Final Note

What I am after from this, would be something like the following

JOB_ID  PK_ID  NOTE
------  -----  --------------
53      1      Some note here
53      1      Another note here
105     2      Noted text
105     3      Final Note

Can anyone advise on how I might achieve this?


Solution

  • Try this works in SQL SERVER

    SELECT 
        [PK_ID]
        ,[JOB_ID]
        ,[NOTE] 
    FROM 
        Table1 
    CROSS APPLY 
    (
        SELECT [NOTE1] AS [NOTE]
        UNION ALL 
        SELECT [NOTE2] AS [NOTE]
    ) T
    WHERE T.NOTE IS NOT NULL
    

    SQL FIDDLE DEMO