I am using Microsoft SQL Server Management Studio 2008.
I have data that looks like this:
Client ID Value
-------------------------------
12345 Did Not Meet
12345 Did Not Meet
12345 Partially Met
12346 Partially Met
12346 Partially Met
12346 Partially Met
12347 Partially Met
12347 Partially Met
12347 Did Not Meet
12347 Met
and I'd like the results to appear like this:
Client ID Value1 Value2 Value3 Value4
12345 Did Not Meet Did Not Meet Partially Met NULL
12346 Partially Met Partially Met Partially Met NULL
12347 Partially Met Partially Met Did Not Meet Met
The columns are unknown so I know I need a dynamic query. I have tried a dynamic query with a pivot function but only got groupings under the same type of value. So the aggregate function worked against me.
This was the query I tried:
Declare @Columns nvarchar(max);
Declare @DynamicPivotQuery nvarchar(max);
Select @Columns=
COALESCE(@Columns+',','')+QUOTENAME(Value)
from (select distinct Document.Value
from Document d
join Client c on d.clientid=c.id
)
as t1
Set @DynamicPivotQuery=
N'Select ClientID, ' + @Columns + '
from
(select Document.ClientID,
DocumentFact.Value,
from Document d
join Client c on d.clientid=c.id
) p
Pivot (max(Value) for Value in ('+@Columns+'))
as pivottable
order by ClientID;'
Exec (@DynamicPivotQuery)
Next I added the row_number and partition functions but can't seem to debug this. The error I get is:
Msg 102, Level 15, State 1, Line 29
Incorrect syntax near ')'.
Which is near the XML Path function.
Any help on this would be appreciated. Thanks.
select @Columns=
COALESCE(@Columns+',','')+QUOTENAME(Value)
from (select distinct Document.Value
, 'name'+ CAST (row_number() over
(Partition BY clientid order by clientid) as NVARCHAR (10)) as Cols
from document d
join Clients c on d.clientid=c.id
t1
--FOR XML PATH('')), 1, 1, N'');
FOR XML PATH('')), TYPE).value('.','NVARCHAR(MAX)'),1,2,'')
order by ClientID
See Question&Answers more detail:
os