Share via

pivot table with dynamically increated column

kasim mohamed 581 Reputation points
2021-07-06T11:02:04.847+00:00

Hi,
I have a table like below
create table #table1 (EmpName varchar(50), Section nvarchar(200));
create table #Result (EmpName varchar(50), Section1 nvarchar(200), Section2 nvarchar(200), Section3 nvarchar(200));

insert into #table1 values ('AAA', '1111')
insert into #table1 values ('AAA', '2222')
insert into #table1 values ('AAA', '3333')

insert into #table1 values ('BBB', '1111')
insert into #table1 values ('BBB', '2222')

insert into #table1 values ('CCC', '3333')

insert into #Result values ('AAA', '1111', '2222', '3333')
insert into #Result values ('BBB', '1111', '2222', '')
select * from #table1;
select * from #Result
drop table #table1;
drop table #Result;

i need the result as Result table. the column count change dynamically.

Thanks

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


2 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2021-07-07T01:43:45.423+00:00

    Please check:

    DECLARE @sql nvarchar(max)  
    DECLARE @s nvarchar(max)  
      
    SELECT @s=STUFF(( SELECT DISTINCT ',['+CAST(Section as nvarchar)+']'  
    FROM #table1 FOR XML PATH('')  ), 1, 1, '')  
          
     SET @sql=N';WITH cte  
     as(SELECT EmpName,CAST(Section as nvarchar) Section  
     FROM #table1)  
       
     SELECT * FROM (SELECT EmpName,Section FROM cte) as t    
     pivot (MAX(Section) FOR Section in ('+@s+')) as p'  
          
     EXECUTE sp_executesql  @sql  
    

    Output:
    112374-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Erland Sommarskog 134.3K Reputation points MVP Volunteer Moderator
    2021-07-06T11:22:16.33+00:00

    I have a primer on how to implement a dynamic pivot here:
    https://www.sommarskog.se/dynamic_sql.html#pivot.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.