Hi @T.Zacks ,
I tried with different methods but failed. I have to add condition 'order=1' and remove the group part in stuff.
Please refer below updated one:
DECLARE @cols AS NVARCHAR(MAX),
@cols1 AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(FieldName)
from DynamicForm
WHERE Ticker='X' AND ClientCode='Z' and [order]=1
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @cols1 = STUFF((SELECT ',max(' + QUOTENAME(FieldName) +') over (partition by Ticker,ClientCode,[order]) '+ QUOTENAME(FieldName)
from DynamicForm
WHERE Ticker='X' AND ClientCode='Z' and [order]=1
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT distinct ' + @cols1 + N' from
(
select *
from DynamicForm WHERE Ticker=''X'' AND ClientCode=''Z''
) x
pivot
(
max(value)
for FieldName in (' + @cols + N')
) p '
exec sp_executesql @query;
Output:
You could check the difference between the two stuffs by executing 'print @Query '.
If we did not add the second stuff using max function , we would get the result like below.
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.