DECLARE
@columns NVARCHAR(MAX) = '',
@columnsname NVARCHAR(MAX) = '',
@columnsnameA NVARCHAR(MAX) = '',
@columnsB NVARCHAR(MAX) = '',
@columnsnameB NVARCHAR(MAX) = '',
@sql NVARCHAR(MAX) = '';
-- select the question num
SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(cast(Question_no as varchar))
FROM submission1_details WHERE Submission1_id=100
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @columnsname = STUFF((SELECT distinct ',' + QUOTENAME(cast(Question_no as varchar)) + ' sub1_Q'+ cast(Question_no as varchar)
FROM submission1_details WHERE Submission1_id=100
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @columnsnameA = STUFF((SELECT distinct ','+' sub1_Q'+ cast(Question_no as varchar)
FROM submission1_details WHERE Submission1_id=100
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @columnsB = STUFF((SELECT distinct ',' + QUOTENAME(cast(Question_no as varchar))
FROM submission2_details WHERE Submission2_id=500
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @columnsnameB = STUFF((SELECT distinct ',' + QUOTENAME(cast(Question_no as varchar)) + ' sub2_Q'+ cast(Question_no as varchar)
FROM submission2_details WHERE Submission2_id=500
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
print @columns
SET @sql ='
select Submission1_id,Submission2_id,Name ,'+ @columnsnameA+ ','[email protected] +' from (
select Submission1_id,Submission2_id,Name ,'[email protected]+',Question_no, Answer from (
select distinct t1.Submission1_id,t1.Submission2_id,Name,t2.Question_no t,t2.Answer A,t3.Question_no,t3.Answer from submission1_header t1
inner JOIN submission1_details t2 ON t1.Submission1_id= t2.Submission1_id
inner JOIN submission2_details t3 ON t1.Submission2_id= t3.Submission2_id
WHERE t1.Submission1_id=100
) as a
PIVOT(
MAX(A)
for t IN ('+ @columns +')
) AS pivot_table
) as b
PIVOT(
MAX(Answer)
for Question_no IN ('+ @columnsB +')
) AS pivot_table1;';
print @sql
-- execute the dynamic SQL
EXECUTE sp_executesql @sql;