简体   繁体   中英

Dynamic sql pivot values coming in seperate columns

HI I am trying to write dynamic pivot as I have over 100 columns

ID   Question    Answer
1    Name        peter
1    DOB         11/12/2003
1    address     …..
1    Issue1      d
1    Issue2      a
2    Name        sam
2    DOB         10/01/1998
2    address     …..
2    Issue1      p
2    Issue2      f

I want the output like this:

ID    Name    DOB         address    Issue1  Issue2
1     peter   11/12/2003    ….       d        a
2     sam     10/01/1998    ….       p        f

Here is the code that I have used:-

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Question) 
                from #temp
                FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = N'SELECT ID + @cols + N' 
            from #temp
        pivot 
        (
            max([answer])
            for Question in (' + @cols + N')
        ) p '

exec sp_executesql @query;

But I am getting each answer in a separate row. I want all the answers of an ID to come in one row. Can somebody help me. Appreciate your time on this. Thank you.

I am getting the output like this, which is not I want. I want the output as above.

ID    Name    DOB       address Issue1    Issue2
1     Peter             
1            11/12/2003         
1                       …       
1                               d   
1                                        a

It looks like you are looking for a way to dynamically create a pivot based on your table without aggregation. You can try the following:

SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Question) 
                    FROM #TEMP
                    GROUP BY QUESTION
                    ORDER BY QUESTION
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ID,' + @cols + ' FROM 
             (
                SELECT ID, Question, Answer
                FROM #TEMP
            ) x
            pivot 
            (
                MAX(Answer)
                for Question in (' + @cols + ')
            ) p '

execute(@query);

Expected Output:

+----+---------+------------+--------+--------+-------+
| ID | address |    DOB     | Issue1 | Issue2 | Name  |
+----+---------+------------+--------+--------+-------+
|  1 | …..     | 11/12/2003 | d      | a      | peter |
|  2 | …..     | 10/1/1998  | p      | f      | sam   |
+----+---------+------------+--------+--------+-------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM