Thanks a lot,
However, does that mean that I would need to insert each element in the Positions field hard-coded? In other words, what if any new position arises tomorrow like Assistant Vice President, or an Officer?
Can a Cross-Apply type or some other technique be applied?
I think if you want the Positions to be dynamic you need to use Dynamic pivot
Thanks to SQLNeophyte for SQL, please POST DDL DML and expected o/p next time
try below
create table test(Department varchar(50), Positions varchar(50),Positionorder int, Members varchar(50)) insert into test values('Dept_A','Assistant_Manager',1,'Employee_A') insert into test values('Dept_A','Manager',2,'Employee_B') insert into test values('Dept_B','Assistant_Manager',1,'Employee_C') insert into test values('Dept_B','Manager',2,'Employee_D') insert into test values('Dept_B','Manager',2,'Employee_E') insert into test values('Dept_C','Manager',2,'Employee_F') insert into test values('Dept_C','Senior_Manager',3,'Employee_G') insert into test values('Dept_C','Senior_Manager',3,'Employee_H') insert into test values('Dept_C','Senior_Manager',3,'Employee_I') -- insert into test values('Dept_C','Assistant Vice President',4,'Employee_J') DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); SET @cols = STUFF((SELECT ',' + QUOTENAME(c.Positions) FROM (select distinct Positions,Positionorder from test ) c order by Positionorder FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query ='with cte as( SELECT Department,Positions, STUFF( (SELECT DISTINCT '','' + Members FROM test WHERE [Department] = a.[Department] AND Positions = a.Positions FOR XML PATH ('''')) , 1, 1, '''') AS Members FROM test AS a GROUP BY Department,Positions ) SELECT * FROM (SELECT Department, Positions,Members FROM cte) AS SourceTable PIVOT ( Max(Members) FOR Positions IN ('+@cols+') ) AS PivotTable;' print @query execute(@query)
Thanks Saravana Kumar C