Search code examples
t-sqlunpivot

how to convert single line SQL result into multiple rows?


I am developing a T-SQL query in SSMS 2008 R2 which returns one line only. But the problem is that in this one line there are four fields which I instead want to be unique rows. For example, my output line looks like:

Col. 1   Col. 2   Col. 3   Col. 4
xxxx     yyyy     zzzz     aaaa

Instead, I want this to look like:

Question    Answer
Col. 1      xxxx
Col. 2      yyyy
Col. 3      zzzz
Col. 4      aaaa

I have tried using the UNPIVOT operator for this, but it is not doing the above. How can I achieve this?


Solution

  • You should be able to use UNPIVOT for this:

    Here is a static pivot where you hard code in the values of the columns:

    create table t1
    (
        col1 varchar(5),
        col2 varchar(5),
        col3 varchar(5),
        col4 varchar(5)
    )
    
    insert into t1 values ('xxxx', 'yyyy', 'zzzz', 'aaaa')
    
    select question, answer
    FROM t1
    unpivot
    (
        answer
        for question in (col1, col2, col3, col4)
    ) u
    
    drop table t1
    

    Here is a SQL Fiddle with a demo.

    but you can also use a Dynamic Unpivot:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);
    
    select @cols = stuff((select ','+quotename(C.name)
             from sys.columns as C
             where C.object_id = object_id('t1') and
                   C.name like 'Col%'
             for xml path('')), 1, 1, '')
    
    set @query = 'SELECT question, answer
                from t1
                unpivot 
                (
                   answer
                   for question in (' + @cols + ')
                ) p '
    
    execute(@query)