MS SQL Server complex pivit with (??STUFF??)

The code below does work and gives me the proper output regardless of how many different QuestionTypes there are
However... If an IndividualID has multiple answers for a particular QuestionType it returns one of them (MAX()

I assume I need a "stuff" statement or coalesce somewhere to put in the column as a comma separated string??
If I add this to the input you will see...

( 2217655 ,101,'VacationActivity' , 'Beach'),
IF OBJECT_ID('tempdb..#table') IS NOT NULL DROP TABLE #table

CREATE TABLE #table
    (
        IndividualID BIGINT ,
        OriginID INT ,
        QuestionType VARCHAR(50) ,
        AnswerText VARCHAR(100)
    );

INSERT INTO #table ( IndividualID ,
                     OriginID ,
                     QuestionType ,
                     AnswerText )
VALUES ( 2217655, 101, 'Age', '25-34' ) ,
       ( 2217655, 101, 'Residence', 'Yes' ) ,
       ( 2217655, 101, 'CardType', 'MasterCard' ) ,
       ( 2217655, 101, 'Income', '$40,000-$49,999' ) ,
       ( 2217655, 101, 'VacationActivity', 'Shopping' ) ,
       ( 2217663, 101, 'Age', '35-44' ) ,
       ( 2217663, 101, 'Residence', 'No' ) ,
       ( 2217663, 101, 'VacationActivity', 'Beachg' );

DECLARE @columns NVARCHAR(MAX) = '';

SELECT @columns += IIF(LEN(@columns) = 0, '', ', ') + '[' + [QuestionType] + ']'
FROM   (   SELECT DISTINCT [QuestionType]
           FROM   #table ) t;

DECLARE @dynamicSQL NVARCHAR(MAX) = 'select [IndividualID], ' + @columns + '
from (
  select [IndividualID], [QuestionType], [AnswerText]
  from #table
  ) src
  pivot
  (
    max([AnswerText])
    for [QuestionType] in ('        + @columns + ')
  )
as pt
';
EXECUTE sp_executesql @dynamicSQL;

DROP TABLE #table; 

Open in new window

Larry Bristersr. DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mark WillsTopic AdvisorCommented:
sitting back enjoying coffee. I have an answer, but waiting to see other posts *laughing*
0
Mark WillsTopic AdvisorCommented:
OK... finished coffee, and have some time then :)

Try
declare  @cols varchar(max)
declare @sql varchar(max)

select @cols = isnull(@cols+',','') + '['+questiontype+']' from #table group by QuestionType
set @sql = '
SELECT  * 
FROM 
(select individualid,originID,questionType,a.answertext from #table T1 
 cross apply (select answertext+'' '' from #table T2 
              where T2.individualid = T1.individualID and T2.originID = t1.originid and t2.questiontype = t1.questiontype for xml path('''')) a(answertext)
 where T1.OriginID = 101 ) src
PIVOT
(max(answertext) for questiontype in ('+@cols+'))pvt'

print @sql


exec(@sql)

Open in new window

And please read the Article : https://www.experts-exchange.com/articles/653/Dynamic-Pivot-Procedure-for-SQL-Server.html

At the moment, "select answertext+'' '' from #table T2 " is space delimited, but if you want comma delimited
declare  @cols varchar(max)
declare @sql varchar(max)

select @cols = isnull(@cols+',','') + '['+questiontype+']' from #table group by QuestionType
set @sql = '
SELECT  * 
FROM 
(select individualid,originID,questionType,stuff(a.answertext,1,2,'''') answertext from #table T1 
 cross apply (select '', ''+answertext from #table T2 
              where T2.individualid = T1.individualID and T2.originID = t1.originid and t2.questiontype = t1.questiontype for xml path('''')) a(answertext)
 where T1.OriginID = 101 ) src
PIVOT
(max(answertext) for questiontype in ('+@cols+'))pvt'

print @sql


exec(@sql)

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Larry Bristersr. DeveloperAuthor Commented:
Beautiful code.
0
Mark WillsTopic AdvisorCommented:
Thankyou, hope it serves you well :)
0
Larry Bristersr. DeveloperAuthor Commented:
Already is...
I am creating one more question in this "arena"
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.